From e4e94aab1f61c0d9aae7284955268e17a5a65a7a Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Thu, 5 Dec 2024 11:19:28 -0500 Subject: [PATCH 01/21] Regenerate off 2025-01, update tests --- codegen/apis | 2 +- pinecone/core/openapi/db_control/__init__.py | 4 +- .../db_control/api/manage_indexes_api.py | 83 ++++- .../db_control/model/collection_list.py | 2 +- .../db_control/model/collection_model.py | 2 +- .../model/configure_index_request.py | 10 +- .../model/configure_index_request_embed.py | 266 ++++++++++++++++ .../model/configure_index_request_spec.py | 2 +- .../model/configure_index_request_spec_pod.py | 2 +- .../model/create_collection_request.py | 2 +- .../model/create_index_for_model_request.py | 300 ++++++++++++++++++ .../create_index_for_model_request_embed.py | 280 ++++++++++++++++ .../db_control/model/create_index_request.py | 24 +- .../db_control/model/deletion_protection.py | 2 +- .../db_control/model/error_response.py | 2 +- .../db_control/model/error_response_error.py | 2 +- .../openapi/db_control/model/index_list.py | 2 +- .../openapi/db_control/model/index_model.py | 36 ++- .../db_control/model/index_model_spec.py | 2 +- .../db_control/model/index_model_status.py | 2 +- .../openapi/db_control/model/index_spec.py | 2 +- .../openapi/db_control/model/index_tags.py | 4 +- .../db_control/model/model_index_embed.py | 286 +++++++++++++++++ .../core/openapi/db_control/model/pod_spec.py | 2 +- .../model/pod_spec_metadata_config.py | 2 +- .../db_control/model/serverless_spec.py | 2 +- .../openapi/db_control/models/__init__.py | 10 + pinecone/core/openapi/db_data/__init__.py | 4 +- .../db_data/api/bulk_operations_api.py | 12 +- .../db_data/api/vector_operations_api.py | 172 +++++++++- .../openapi/db_data/model/delete_request.py | 6 +- .../model/describe_index_stats_request.py | 6 +- .../openapi/db_data/model/fetch_response.py | 2 +- pinecone/core/openapi/db_data/model/hit.py | 272 ++++++++++++++++ .../db_data/model/import_error_mode.py | 2 +- .../openapi/db_data/model/import_model.py | 2 +- .../db_data/model/index_description.py | 18 +- .../db_data/model/list_imports_response.py | 2 +- .../core/openapi/db_data/model/list_item.py | 2 +- .../openapi/db_data/model/list_response.py | 2 +- .../db_data/model/namespace_summary.py | 2 +- .../core/openapi/db_data/model/pagination.py | 2 +- .../openapi/db_data/model/protobuf_any.py | 2 +- .../db_data/model/protobuf_null_value.py | 2 +- .../openapi/db_data/model/query_request.py | 6 +- .../openapi/db_data/model/query_response.py | 2 +- .../openapi/db_data/model/query_vector.py | 2 +- .../core/openapi/db_data/model/rpc_status.py | 2 +- .../openapi/db_data/model/scored_vector.py | 2 +- .../db_data/model/search_records_request.py | 282 ++++++++++++++++ .../model/search_records_request_query.py | 280 ++++++++++++++++ .../model/search_records_request_rerank.py | 274 ++++++++++++++++ .../db_data/model/search_records_response.py | 278 ++++++++++++++++ .../model/search_records_response_result.py | 268 ++++++++++++++++ .../openapi/db_data/model/search_usage.py | 272 ++++++++++++++++ .../openapi/db_data/model/search_vector.py | 262 +++++++++++++++ .../db_data/model/single_query_results.py | 2 +- .../openapi/db_data/model/sparse_values.py | 2 +- .../db_data/model/start_import_request.py | 2 +- .../db_data/model/start_import_response.py | 2 +- .../openapi/db_data/model/update_request.py | 2 +- .../openapi/db_data/model/upsert_record.py | 278 ++++++++++++++++ .../db_data/model/upsert_record_embed.py | 254 +++++++++++++++ .../openapi/db_data/model/upsert_request.py | 2 +- .../openapi/db_data/model/upsert_response.py | 2 +- pinecone/core/openapi/db_data/model/usage.py | 2 +- pinecone/core/openapi/db_data/model/vector.py | 2 +- .../openapi/db_data/model/vector_values.py | 272 ++++++++++++++++ .../core/openapi/db_data/models/__init__.py | 17 + tests/unit/openapi_support/test_api_client.py | 22 ++ 70 files changed, 4542 insertions(+), 94 deletions(-) create mode 100644 pinecone/core/openapi/db_control/model/configure_index_request_embed.py create mode 100644 pinecone/core/openapi/db_control/model/create_index_for_model_request.py create mode 100644 pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py create mode 100644 pinecone/core/openapi/db_control/model/model_index_embed.py create mode 100644 pinecone/core/openapi/db_data/model/hit.py create mode 100644 pinecone/core/openapi/db_data/model/search_records_request.py create mode 100644 pinecone/core/openapi/db_data/model/search_records_request_query.py create mode 100644 pinecone/core/openapi/db_data/model/search_records_request_rerank.py create mode 100644 pinecone/core/openapi/db_data/model/search_records_response.py create mode 100644 pinecone/core/openapi/db_data/model/search_records_response_result.py create mode 100644 pinecone/core/openapi/db_data/model/search_usage.py create mode 100644 pinecone/core/openapi/db_data/model/search_vector.py create mode 100644 pinecone/core/openapi/db_data/model/upsert_record.py create mode 100644 pinecone/core/openapi/db_data/model/upsert_record_embed.py create mode 100644 pinecone/core/openapi/db_data/model/vector_values.py diff --git a/codegen/apis b/codegen/apis index 38acd80d9..09510b5d4 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 38acd80d935f556c115ec53aa2b4a0d80c8d8da4 +Subproject commit 09510b5d4074ea00ccdf9dffcc13e05c14c91344 diff --git a/pinecone/core/openapi/db_control/__init__.py b/pinecone/core/openapi/db_control/__init__.py index b142fc572..56ed06a91 100644 --- a/pinecone/core/openapi/db_control/__init__.py +++ b/pinecone/core/openapi/db_control/__init__.py @@ -5,7 +5,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -26,4 +26,4 @@ from pinecone.openapi_support.exceptions import PineconeApiKeyError from pinecone.openapi_support.exceptions import PineconeApiException -API_VERSION = "2024-10" +API_VERSION = "2025-01" diff --git a/pinecone/core/openapi/db_control/api/manage_indexes_api.py b/pinecone/core/openapi/db_control/api/manage_indexes_api.py index 77c71102a..425ef7456 100644 --- a/pinecone/core/openapi/db_control/api/manage_indexes_api.py +++ b/pinecone/core/openapi/db_control/api/manage_indexes_api.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -25,6 +25,9 @@ from pinecone.core.openapi.db_control.model.collection_model import CollectionModel from pinecone.core.openapi.db_control.model.configure_index_request import ConfigureIndexRequest from pinecone.core.openapi.db_control.model.create_collection_request import CreateCollectionRequest +from pinecone.core.openapi.db_control.model.create_index_for_model_request import ( + CreateIndexForModelRequest, +) from pinecone.core.openapi.db_control.model.create_index_request import CreateIndexRequest from pinecone.core.openapi.db_control.model.error_response import ErrorResponse from pinecone.core.openapi.db_control.model.index_list import IndexList @@ -282,6 +285,84 @@ def __create_index(self, create_index_request, **kwargs): callable=__create_index, ) + def __create_index_for_model(self, create_index_for_model_request, **kwargs): + """Create an index for an embedding model # noqa: E501 + + This operation creates a serverless index configured for a specific embedding model. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_index_for_model(create_index_for_model_request, async_req=True) + >>> result = thread.get() + + Args: + create_index_for_model_request (CreateIndexForModelRequest): The desired configuration for the index and associated embedding model. + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + IndexModel + If the method is called asynchronously, returns the request + thread. + """ + kwargs["async_req"] = kwargs.get("async_req", False) + kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) + kwargs["_preload_content"] = kwargs.get("_preload_content", True) + kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) + kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) + kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) + kwargs["_host_index"] = kwargs.get("_host_index") + kwargs["create_index_for_model_request"] = create_index_for_model_request + return self.call_with_http_info(**kwargs) + + self.create_index_for_model = _Endpoint( + settings={ + "response_type": (IndexModel,), + "auth": ["ApiKeyAuth"], + "endpoint_path": "/indexes/create-for-model", + "operation_id": "create_index_for_model", + "http_method": "POST", + "servers": None, + }, + params_map={ + "all": ["create_index_for_model_request"], + "required": ["create_index_for_model_request"], + "nullable": [], + "enum": [], + "validation": [], + }, + root_map={ + "validations": {}, + "allowed_values": {}, + "openapi_types": {"create_index_for_model_request": (CreateIndexForModelRequest,)}, + "attribute_map": {}, + "location_map": {"create_index_for_model_request": "body"}, + "collection_format_map": {}, + }, + headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, + api_client=api_client, + callable=__create_index_for_model, + ) + def __delete_collection(self, collection_name, **kwargs): """Delete a collection # noqa: E501 diff --git a/pinecone/core/openapi/db_control/model/collection_list.py b/pinecone/core/openapi/db_control/model/collection_list.py index 7997edce9..1d17d737d 100644 --- a/pinecone/core/openapi/db_control/model/collection_list.py +++ b/pinecone/core/openapi/db_control/model/collection_list.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/collection_model.py b/pinecone/core/openapi/db_control/model/collection_model.py index 5dd8f5af1..76967bd59 100644 --- a/pinecone/core/openapi/db_control/model/collection_model.py +++ b/pinecone/core/openapi/db_control/model/collection_model.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/configure_index_request.py b/pinecone/core/openapi/db_control/model/configure_index_request.py index 042600c88..b6753c328 100644 --- a/pinecone/core/openapi/db_control/model/configure_index_request.py +++ b/pinecone/core/openapi/db_control/model/configure_index_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -30,12 +30,16 @@ def lazy_import(): + from pinecone.core.openapi.db_control.model.configure_index_request_embed import ( + ConfigureIndexRequestEmbed, + ) from pinecone.core.openapi.db_control.model.configure_index_request_spec import ( ConfigureIndexRequestSpec, ) from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection from pinecone.core.openapi.db_control.model.index_tags import IndexTags + globals()["ConfigureIndexRequestEmbed"] = ConfigureIndexRequestEmbed globals()["ConfigureIndexRequestSpec"] = ConfigureIndexRequestSpec globals()["DeletionProtection"] = DeletionProtection globals()["IndexTags"] = IndexTags @@ -95,6 +99,7 @@ def openapi_types(): "spec": (ConfigureIndexRequestSpec,), # noqa: E501 "deletion_protection": (DeletionProtection,), # noqa: E501 "tags": (IndexTags,), # noqa: E501 + "embed": (ConfigureIndexRequestEmbed,), # noqa: E501 } @cached_property @@ -105,6 +110,7 @@ def discriminator(): "spec": "spec", # noqa: E501 "deletion_protection": "deletion_protection", # noqa: E501 "tags": "tags", # noqa: E501 + "embed": "embed", # noqa: E501 } read_only_vars = {} @@ -150,6 +156,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + embed (ConfigureIndexRequestEmbed): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -236,6 +243,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + embed (ConfigureIndexRequestEmbed): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_embed.py b/pinecone/core/openapi/db_control/model/configure_index_request_embed.py new file mode 100644 index 000000000..3a76ea6de --- /dev/null +++ b/pinecone/core/openapi/db_control/model/configure_index_request_embed.py @@ -0,0 +1,266 @@ +""" +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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class ConfigureIndexRequestEmbed(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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, 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 { + "model": (str,), # noqa: E501 + "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "model": "model", # noqa: E501 + "field_map": "field_map", # noqa: E501 + "read_parameters": "read_parameters", # noqa: E501 + "write_parameters": "write_parameters", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ConfigureIndexRequestEmbed - a model defined in OpenAPI + + Keyword Args: + _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,) + model (str): The name of the embedding model to use with the index. The index dimension and model dimension must match, and the index similarity metric must be supported by the model. The index embedding model cannot be changed once set.. [optional] # noqa: E501 + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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): # noqa: E501 + """ConfigureIndexRequestEmbed - a model defined in OpenAPI + + Keyword Args: + _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,) + model (str): The name of the embedding model to use with the index. The index dimension and model dimension must match, and the index similarity metric must be supported by the model. The index embedding model cannot be changed once set.. [optional] # noqa: E501 + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_spec.py b/pinecone/core/openapi/db_control/model/configure_index_request_spec.py index b5e0b115c..bea615c8f 100644 --- a/pinecone/core/openapi/db_control/model/configure_index_request_spec.py +++ b/pinecone/core/openapi/db_control/model/configure_index_request_spec.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py b/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py index 01793eb51..51e1c8a02 100644 --- a/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py +++ b/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/create_collection_request.py b/pinecone/core/openapi/db_control/model/create_collection_request.py index 0677a63df..3c2441965 100644 --- a/pinecone/core/openapi/db_control/model/create_collection_request.py +++ b/pinecone/core/openapi/db_control/model/create_collection_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/create_index_for_model_request.py b/pinecone/core/openapi/db_control/model/create_index_for_model_request.py new file mode 100644 index 000000000..f10c9c116 --- /dev/null +++ b/pinecone/core/openapi/db_control/model/create_index_for_model_request.py @@ -0,0 +1,300 @@ +""" +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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_control.model.create_index_for_model_request_embed import ( + CreateIndexForModelRequestEmbed, + ) + from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection + from pinecone.core.openapi.db_control.model.index_tags import IndexTags + + globals()["CreateIndexForModelRequestEmbed"] = CreateIndexForModelRequestEmbed + globals()["DeletionProtection"] = DeletionProtection + globals()["IndexTags"] = IndexTags + + +class CreateIndexForModelRequest(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {("cloud",): {"GCP": "gcp", "AWS": "aws", "AZURE": "azure"}} + + validations = {("name",): {"max_length": 45, "min_length": 1}} + + @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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "name": (str,), # noqa: E501 + "cloud": (str,), # noqa: E501 + "region": (str,), # noqa: E501 + "embed": (CreateIndexForModelRequestEmbed,), # noqa: E501 + "deletion_protection": (DeletionProtection,), # noqa: E501 + "tags": (IndexTags,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "name": "name", # noqa: E501 + "cloud": "cloud", # noqa: E501 + "region": "region", # noqa: E501 + "embed": "embed", # noqa: E501 + "deletion_protection": "deletion_protection", # noqa: E501 + "tags": "tags", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, cloud, region, embed, *args, **kwargs): # noqa: E501 + """CreateIndexForModelRequest - a model defined in OpenAPI + + Args: + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + 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. + embed (CreateIndexForModelRequestEmbed): + + Keyword Args: + _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,) + deletion_protection (DeletionProtection): [optional] # noqa: E501 + tags (IndexTags): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.name = name + self.cloud = cloud + self.region = region + self.embed = embed + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, name, cloud, region, embed, *args, **kwargs): # noqa: E501 + """CreateIndexForModelRequest - a model defined in OpenAPI + + Args: + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + 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. + embed (CreateIndexForModelRequestEmbed): + + Keyword Args: + _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,) + deletion_protection (DeletionProtection): [optional] # noqa: E501 + tags (IndexTags): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.name = name + self.cloud = cloud + self.region = region + self.embed = embed + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py b/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py new file mode 100644 index 000000000..d2d34aa1b --- /dev/null +++ b/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py @@ -0,0 +1,280 @@ +""" +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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class CreateIndexForModelRequestEmbed(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = { + ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} + } + + 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, 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 { + "model": (str,), # noqa: E501 + "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "metric": (str,), # noqa: E501 + "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "model": "model", # noqa: E501 + "field_map": "field_map", # noqa: E501 + "metric": "metric", # noqa: E501 + "read_parameters": "read_parameters", # noqa: E501 + "write_parameters": "write_parameters", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, model, field_map, *args, **kwargs): # noqa: E501 + """CreateIndexForModelRequestEmbed - a model defined in OpenAPI + + Args: + model (str): The name of the embedding model to use for the index. + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. + + Keyword Args: + _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,) + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.model = model + self.field_map = field_map + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, model, field_map, *args, **kwargs): # noqa: E501 + """CreateIndexForModelRequestEmbed - a model defined in OpenAPI + + Args: + model (str): The name of the embedding model to use for the index. + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. + + Keyword Args: + _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,) + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.model = model + self.field_map = field_map + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_control/model/create_index_request.py b/pinecone/core/openapi/db_control/model/create_index_request.py index 815d09311..42b6c6128 100644 --- a/pinecone/core/openapi/db_control/model/create_index_request.py +++ b/pinecone/core/openapi/db_control/model/create_index_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -96,11 +96,12 @@ def openapi_types(): lazy_import() return { "name": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 "spec": (IndexSpec,), # noqa: E501 + "dimension": (int,), # noqa: E501 "metric": (str,), # noqa: E501 "deletion_protection": (DeletionProtection,), # noqa: E501 "tags": (IndexTags,), # noqa: E501 + "vector_type": (str,), # noqa: E501 } @cached_property @@ -109,11 +110,12 @@ def discriminator(): attribute_map = { "name": "name", # noqa: E501 - "dimension": "dimension", # noqa: E501 "spec": "spec", # noqa: E501 + "dimension": "dimension", # noqa: E501 "metric": "metric", # noqa: E501 "deletion_protection": "deletion_protection", # noqa: E501 "tags": "tags", # noqa: E501 + "vector_type": "vector_type", # noqa: E501 } read_only_vars = {} @@ -122,12 +124,11 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, spec, *args, **kwargs): # noqa: E501 """CreateIndexRequest - a model defined in OpenAPI Args: name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. spec (IndexSpec): Keyword Args: @@ -161,9 +162,11 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 Animal class but this time we won't travel 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 + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'.. [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. [optional] if omitted the server will use the default value of "dense" # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -190,7 +193,6 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.dimension = dimension self.spec = spec for var_name, var_value in kwargs.items(): if ( @@ -216,12 +218,11 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 ) @convert_js_args_to_python_args - def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 + def __init__(self, name, spec, *args, **kwargs): # noqa: E501 """CreateIndexRequest - a model defined in OpenAPI Args: name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. spec (IndexSpec): Keyword Args: @@ -255,9 +256,11 @@ def __init__(self, name, dimension, 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,) - 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 + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'.. [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. [optional] if omitted the server will use the default value of "dense" # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -282,7 +285,6 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.dimension = dimension self.spec = spec for var_name, var_value in kwargs.items(): if ( diff --git a/pinecone/core/openapi/db_control/model/deletion_protection.py b/pinecone/core/openapi/db_control/model/deletion_protection.py index 9b3a72557..0bb89cd0e 100644 --- a/pinecone/core/openapi/db_control/model/deletion_protection.py +++ b/pinecone/core/openapi/db_control/model/deletion_protection.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/error_response.py b/pinecone/core/openapi/db_control/model/error_response.py index a03563f71..93a05c443 100644 --- a/pinecone/core/openapi/db_control/model/error_response.py +++ b/pinecone/core/openapi/db_control/model/error_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/error_response_error.py b/pinecone/core/openapi/db_control/model/error_response_error.py index 1e002870d..99138ff3e 100644 --- a/pinecone/core/openapi/db_control/model/error_response_error.py +++ b/pinecone/core/openapi/db_control/model/error_response_error.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/index_list.py b/pinecone/core/openapi/db_control/model/index_list.py index 865e00db0..553899272 100644 --- a/pinecone/core/openapi/db_control/model/index_list.py +++ b/pinecone/core/openapi/db_control/model/index_list.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/index_model.py b/pinecone/core/openapi/db_control/model/index_model.py index 95879ae7a..06a77d298 100644 --- a/pinecone/core/openapi/db_control/model/index_model.py +++ b/pinecone/core/openapi/db_control/model/index_model.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -34,11 +34,13 @@ def lazy_import(): from pinecone.core.openapi.db_control.model.index_model_spec import IndexModelSpec from pinecone.core.openapi.db_control.model.index_model_status import IndexModelStatus from pinecone.core.openapi.db_control.model.index_tags import IndexTags + from pinecone.core.openapi.db_control.model.model_index_embed import ModelIndexEmbed globals()["DeletionProtection"] = DeletionProtection globals()["IndexModelSpec"] = IndexModelSpec globals()["IndexModelStatus"] = IndexModelStatus globals()["IndexTags"] = IndexTags + globals()["ModelIndexEmbed"] = ModelIndexEmbed class IndexModel(ModelNormal): @@ -98,13 +100,15 @@ def openapi_types(): lazy_import() return { "name": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 "metric": (str,), # noqa: E501 "host": (str,), # noqa: E501 "spec": (IndexModelSpec,), # noqa: E501 "status": (IndexModelStatus,), # noqa: E501 + "vector_type": (str,), # noqa: E501 + "dimension": (int,), # noqa: E501 "deletion_protection": (DeletionProtection,), # noqa: E501 "tags": (IndexTags,), # noqa: E501 + "embed": (ModelIndexEmbed,), # noqa: E501 } @cached_property @@ -113,13 +117,15 @@ def discriminator(): attribute_map = { "name": "name", # noqa: E501 - "dimension": "dimension", # noqa: E501 "metric": "metric", # noqa: E501 "host": "host", # noqa: E501 "spec": "spec", # noqa: E501 "status": "status", # noqa: E501 + "vector_type": "vector_type", # noqa: E501 + "dimension": "dimension", # noqa: E501 "deletion_protection": "deletion_protection", # noqa: E501 "tags": "tags", # noqa: E501 + "embed": "embed", # noqa: E501 } read_only_vars = {} @@ -128,18 +134,18 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. defaults to "dense" # 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. @@ -170,11 +176,13 @@ 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,) + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + embed (ModelIndexEmbed): [optional] # noqa: E501 """ - metric = kwargs.get("metric", "cosine") + vector_type = kwargs.get("vector_type", "dense") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) @@ -199,11 +207,11 @@ def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.dimension = dimension self.metric = metric self.host = host self.spec = spec self.status = status + self.vector_type = vector_type for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map @@ -228,18 +236,18 @@ def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs ) @convert_js_args_to_python_args - def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 + def __init__(self, name, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. defaults to "dense" # 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. @@ -270,11 +278,13 @@ 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,) + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 deletion_protection (DeletionProtection): [optional] # noqa: E501 tags (IndexTags): [optional] # noqa: E501 + embed (ModelIndexEmbed): [optional] # noqa: E501 """ - metric = kwargs.get("metric", "cosine") + vector_type = kwargs.get("vector_type", "dense") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) @@ -297,11 +307,11 @@ def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noq self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.dimension = dimension self.metric = metric self.host = host self.spec = spec self.status = status + self.vector_type = vector_type for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map diff --git a/pinecone/core/openapi/db_control/model/index_model_spec.py b/pinecone/core/openapi/db_control/model/index_model_spec.py index 086ff60e8..e7098eaca 100644 --- a/pinecone/core/openapi/db_control/model/index_model_spec.py +++ b/pinecone/core/openapi/db_control/model/index_model_spec.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/index_model_status.py b/pinecone/core/openapi/db_control/model/index_model_status.py index 012659124..3ebd55aaa 100644 --- a/pinecone/core/openapi/db_control/model/index_model_status.py +++ b/pinecone/core/openapi/db_control/model/index_model_status.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/index_spec.py b/pinecone/core/openapi/db_control/model/index_spec.py index 58afeca7a..e928c2dbd 100644 --- a/pinecone/core/openapi/db_control/model/index_spec.py +++ b/pinecone/core/openapi/db_control/model/index_spec.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/index_tags.py b/pinecone/core/openapi/db_control/model/index_tags.py index 1ea5266ec..77dd7bd93 100644 --- a/pinecone/core/openapi/db_control/model/index_tags.py +++ b/pinecone/core/openapi/db_control/model/index_tags.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -65,7 +65,7 @@ def additional_properties_type(): """ return (str,) # noqa: E501 - _nullable = True + _nullable = False @cached_property def openapi_types(): diff --git a/pinecone/core/openapi/db_control/model/model_index_embed.py b/pinecone/core/openapi/db_control/model/model_index_embed.py new file mode 100644 index 000000000..9dc6e4911 --- /dev/null +++ b/pinecone/core/openapi/db_control/model/model_index_embed.py @@ -0,0 +1,286 @@ +""" +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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class ModelIndexEmbed(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = { + ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} + } + + validations = {("dimension",): {"inclusive_maximum": 20000, "inclusive_minimum": 1}} + + @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, 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 { + "model": (str,), # noqa: E501 + "metric": (str,), # noqa: E501 + "dimension": (int,), # noqa: E501 + "vector_type": (str,), # noqa: E501 + "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "model": "model", # noqa: E501 + "metric": "metric", # noqa: E501 + "dimension": "dimension", # noqa: E501 + "vector_type": "vector_type", # noqa: E501 + "field_map": "field_map", # noqa: E501 + "read_parameters": "read_parameters", # noqa: E501 + "write_parameters": "write_parameters", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, model, *args, **kwargs): # noqa: E501 + """ModelIndexEmbed - a model defined in OpenAPI + + Args: + model (str): The name of the embedding model used to create the index. + + Keyword Args: + _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,) + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set.. [optional] # noqa: E501 + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. [optional] if omitted the server will use the default value of "dense" # noqa: E501 + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that is embedded.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.model = model + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, model, *args, **kwargs): # noqa: E501 + """ModelIndexEmbed - a model defined in OpenAPI + + Args: + model (str): The name of the embedding model used to create the index. + + Keyword Args: + _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,) + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set.. [optional] # noqa: E501 + dimension (int): The dimensions of the vectors to be inserted in the index.. [optional] # noqa: E501 + vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified.. [optional] if omitted the server will use the default value of "dense" # noqa: E501 + field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that is embedded.. [optional] # noqa: E501 + read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model.. [optional] # noqa: E501 + write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.model = model + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_control/model/pod_spec.py b/pinecone/core/openapi/db_control/model/pod_spec.py index 2ba224d77..b0bd55145 100644 --- a/pinecone/core/openapi/db_control/model/pod_spec.py +++ b/pinecone/core/openapi/db_control/model/pod_spec.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py b/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py index 007f30efa..dc040fb58 100644 --- a/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py +++ b/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/model/serverless_spec.py b/pinecone/core/openapi/db_control/model/serverless_spec.py index f5841c56b..630d6334c 100644 --- a/pinecone/core/openapi/db_control/model/serverless_spec.py +++ b/pinecone/core/openapi/db_control/model/serverless_spec.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_control/models/__init__.py b/pinecone/core/openapi/db_control/models/__init__.py index 44249eb16..fd82f1214 100644 --- a/pinecone/core/openapi/db_control/models/__init__.py +++ b/pinecone/core/openapi/db_control/models/__init__.py @@ -12,6 +12,9 @@ from pinecone.core.openapi.db_control.model.collection_list import CollectionList from pinecone.core.openapi.db_control.model.collection_model import CollectionModel from pinecone.core.openapi.db_control.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.openapi.db_control.model.configure_index_request_embed import ( + ConfigureIndexRequestEmbed, +) from pinecone.core.openapi.db_control.model.configure_index_request_spec import ( ConfigureIndexRequestSpec, ) @@ -19,6 +22,12 @@ ConfigureIndexRequestSpecPod, ) from pinecone.core.openapi.db_control.model.create_collection_request import CreateCollectionRequest +from pinecone.core.openapi.db_control.model.create_index_for_model_request import ( + CreateIndexForModelRequest, +) +from pinecone.core.openapi.db_control.model.create_index_for_model_request_embed import ( + CreateIndexForModelRequestEmbed, +) from pinecone.core.openapi.db_control.model.create_index_request import CreateIndexRequest from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection from pinecone.core.openapi.db_control.model.error_response import ErrorResponse @@ -29,6 +38,7 @@ from pinecone.core.openapi.db_control.model.index_model_status import IndexModelStatus from pinecone.core.openapi.db_control.model.index_spec import IndexSpec from pinecone.core.openapi.db_control.model.index_tags import IndexTags +from pinecone.core.openapi.db_control.model.model_index_embed import ModelIndexEmbed from pinecone.core.openapi.db_control.model.pod_spec import PodSpec from pinecone.core.openapi.db_control.model.pod_spec_metadata_config import PodSpecMetadataConfig from pinecone.core.openapi.db_control.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/openapi/db_data/__init__.py b/pinecone/core/openapi/db_data/__init__.py index e19083f06..a6e9102ef 100644 --- a/pinecone/core/openapi/db_data/__init__.py +++ b/pinecone/core/openapi/db_data/__init__.py @@ -5,7 +5,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -26,4 +26,4 @@ from pinecone.openapi_support.exceptions import PineconeApiKeyError from pinecone.openapi_support.exceptions import PineconeApiException -API_VERSION = "2024-10" +API_VERSION = "2025-01" diff --git a/pinecone/core/openapi/db_data/api/bulk_operations_api.py b/pinecone/core/openapi/db_data/api/bulk_operations_api.py index ab391fee0..2cacb296d 100644 --- a/pinecone/core/openapi/db_data/api/bulk_operations_api.py +++ b/pinecone/core/openapi/db_data/api/bulk_operations_api.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -43,7 +43,7 @@ def __init__(self, api_client=None): def __cancel_bulk_import(self, id, **kwargs): """Cancel an import # noqa: E501 - The `cancel_import` operation cancels an import operation if it is not yet finished. It has no effect if the operation is already finished. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 + The `cancel_import` operation cancels an import operation if it is not yet finished. It has no effect if the operation is already finished. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -121,7 +121,7 @@ def __cancel_bulk_import(self, id, **kwargs): def __describe_bulk_import(self, id, **kwargs): """Describe an import # noqa: E501 - The `describe_import` operation returns details of a specific import operation. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 + The `describe_import` operation returns details of a specific import operation. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -129,7 +129,7 @@ def __describe_bulk_import(self, id, **kwargs): >>> result = thread.get() Args: - id (str): + id (str): Unique identifier for the import operation. Keyword Args: _return_http_data_only (bool): response data without head status @@ -199,7 +199,7 @@ def __describe_bulk_import(self, id, **kwargs): def __list_bulk_imports(self, **kwargs): """List imports # noqa: E501 - The `list_imports` operation lists all recent and ongoing import operations. By default, `list_imports` returns up to 100 imports per page. If the `limit` parameter is set, `list` returns up to that number of imports instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of imports. When the response does not include a `pagination_token`, there are no more imports to return. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 + The `list_imports` operation lists all recent and ongoing import operations. By default, `list_imports` returns up to 100 imports per page. If the `limit` parameter is set, `list` returns up to that number of imports instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of imports. When the response does not include a `pagination_token`, there are no more imports to return. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -276,7 +276,7 @@ def __list_bulk_imports(self, **kwargs): def __start_bulk_import(self, start_import_request, **kwargs): """Start import # noqa: E501 - The `start_import` operation starts an asynchronous import of vectors from object storage into an index. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 + The `start_import` operation starts an asynchronous import of vectors from object storage into an index. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True diff --git a/pinecone/core/openapi/db_data/api/vector_operations_api.py b/pinecone/core/openapi/db_data/api/vector_operations_api.py index 2979d1fe5..ce216d7d7 100644 --- a/pinecone/core/openapi/db_data/api/vector_operations_api.py +++ b/pinecone/core/openapi/db_data/api/vector_operations_api.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -31,7 +31,10 @@ from pinecone.core.openapi.db_data.model.query_request import QueryRequest from pinecone.core.openapi.db_data.model.query_response import QueryResponse from pinecone.core.openapi.db_data.model.rpc_status import RpcStatus +from pinecone.core.openapi.db_data.model.search_records_request import SearchRecordsRequest +from pinecone.core.openapi.db_data.model.search_records_response import SearchRecordsResponse from pinecone.core.openapi.db_data.model.update_request import UpdateRequest +from pinecone.core.openapi.db_data.model.upsert_record import UpsertRecord from pinecone.core.openapi.db_data.model.upsert_request import UpsertRequest from pinecone.core.openapi.db_data.model.upsert_response import UpsertResponse @@ -129,7 +132,7 @@ def __delete_vectors(self, delete_request, **kwargs): def __describe_index_stats(self, describe_index_stats_request, **kwargs): """Get index stats # noqa: E501 - The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. For pod-based indexes, the index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index). # noqa: E501 + The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -286,7 +289,7 @@ def __fetch_vectors(self, ids, **kwargs): def __list_vectors(self, **kwargs): """List vector IDs # noqa: E501 - The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. By default, `list` returns up to 100 IDs per page in sorted order (bitwise \"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list_vectors` is supported only for serverless indexes. # noqa: E501 + The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. `list` returns up to 100 IDs at a time by default in sorted order (bitwise \"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list` is supported only for serverless indexes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -455,6 +458,89 @@ def __query_vectors(self, query_request, **kwargs): callable=__query_vectors, ) + def __search_records_namespace(self, namespace, search_records_request, **kwargs): + """Search a namespace # noqa: E501 + + This operation converts a query to a vector embedding and then searches a namespace using the embedding. It returns the most similar records in the namespace, along with their similarity scores. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.search_records_namespace(namespace, search_records_request, async_req=True) + >>> result = thread.get() + + Args: + namespace (str): The namespace to search. + search_records_request (SearchRecordsRequest): + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + SearchRecordsResponse + If the method is called asynchronously, returns the request + thread. + """ + kwargs["async_req"] = kwargs.get("async_req", False) + kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) + kwargs["_preload_content"] = kwargs.get("_preload_content", True) + kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) + kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) + kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) + kwargs["_host_index"] = kwargs.get("_host_index") + kwargs["namespace"] = namespace + kwargs["search_records_request"] = search_records_request + return self.call_with_http_info(**kwargs) + + self.search_records_namespace = _Endpoint( + settings={ + "response_type": (SearchRecordsResponse,), + "auth": ["ApiKeyAuth"], + "endpoint_path": "/records/namespaces/{namespace}/search", + "operation_id": "search_records_namespace", + "http_method": "POST", + "servers": None, + }, + params_map={ + "all": ["namespace", "search_records_request"], + "required": ["namespace", "search_records_request"], + "nullable": [], + "enum": [], + "validation": [], + }, + root_map={ + "validations": {}, + "allowed_values": {}, + "openapi_types": { + "namespace": (str,), + "search_records_request": (SearchRecordsRequest,), + }, + "attribute_map": {"namespace": "namespace"}, + "location_map": {"namespace": "path", "search_records_request": "body"}, + "collection_format_map": {}, + }, + headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, + api_client=api_client, + callable=__search_records_namespace, + ) + def __update_vector(self, update_request, **kwargs): """Update a vector # noqa: E501 @@ -533,6 +619,86 @@ def __update_vector(self, update_request, **kwargs): callable=__update_vector, ) + def __upsert_records_namespace(self, namespace, upsert_record, **kwargs): + """Upsert records into a namespace # noqa: E501 + + This operation converts input data to vector embeddings and then upserts the embeddings into a namespace. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upsert_records_namespace(namespace, upsert_record, async_req=True) + >>> result = thread.get() + + Args: + namespace (str): The namespace to upsert records into. + upsert_record ([UpsertRecord]): + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs["async_req"] = kwargs.get("async_req", False) + kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) + kwargs["_preload_content"] = kwargs.get("_preload_content", True) + kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) + kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) + kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) + kwargs["_host_index"] = kwargs.get("_host_index") + kwargs["namespace"] = namespace + kwargs["upsert_record"] = upsert_record + return self.call_with_http_info(**kwargs) + + self.upsert_records_namespace = _Endpoint( + settings={ + "response_type": None, + "auth": ["ApiKeyAuth"], + "endpoint_path": "/records/namespaces/{namespace}/upsert", + "operation_id": "upsert_records_namespace", + "http_method": "POST", + "servers": None, + }, + params_map={ + "all": ["namespace", "upsert_record"], + "required": ["namespace", "upsert_record"], + "nullable": [], + "enum": [], + "validation": [], + }, + root_map={ + "validations": {}, + "allowed_values": {}, + "openapi_types": {"namespace": (str,), "upsert_record": ([UpsertRecord],)}, + "attribute_map": {"namespace": "namespace"}, + "location_map": {"namespace": "path", "upsert_record": "body"}, + "collection_format_map": {}, + }, + headers_map={"accept": ["application/json"], "content_type": ["application/x-ndjson"]}, + api_client=api_client, + callable=__upsert_records_namespace, + ) + def __upsert_vectors(self, upsert_request, **kwargs): """Upsert vectors # noqa: E501 diff --git a/pinecone/core/openapi/db_data/model/delete_request.py b/pinecone/core/openapi/db_data/model/delete_request.py index 6412b708c..47ffecc62 100644 --- a/pinecone/core/openapi/db_data/model/delete_request.py +++ b/pinecone/core/openapi/db_data/model/delete_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -138,7 +138,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -225,7 +225,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/db_data/model/describe_index_stats_request.py b/pinecone/core/openapi/db_data/model/describe_index_stats_request.py index 0a1b2bfe7..3dbd0fdb6 100644 --- a/pinecone/core/openapi/db_data/model/describe_index_stats_request.py +++ b/pinecone/core/openapi/db_data/model/describe_index_stats_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -129,7 +129,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - filter ({str: (bool, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -213,7 +213,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - filter ({str: (bool, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/db_data/model/fetch_response.py b/pinecone/core/openapi/db_data/model/fetch_response.py index 8bcd3fe3b..cfe22cdf3 100644 --- a/pinecone/core/openapi/db_data/model/fetch_response.py +++ b/pinecone/core/openapi/db_data/model/fetch_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/hit.py b/pinecone/core/openapi/db_data/model/hit.py new file mode 100644 index 000000000..93583fdba --- /dev/null +++ b/pinecone/core/openapi/db_data/model/hit.py @@ -0,0 +1,272 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class Hit(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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, 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 { + "id": (str,), # noqa: E501 + "score": (float,), # noqa: E501 + "fields": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "id": "_id", # noqa: E501 + "score": "_score", # noqa: E501 + "fields": "fields", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, id, score, fields, *args, **kwargs): # noqa: E501 + """Hit - a model defined in OpenAPI + + Args: + id (str): The record id of the search hit. + score (float): The similarity score of the returned record. + fields ({str: (bool, dict, float, int, list, str, none_type)}): The selected record fields associated with the search hit. + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.id = id + self.score = score + self.fields = fields + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, id, score, fields, *args, **kwargs): # noqa: E501 + """Hit - a model defined in OpenAPI + + Args: + id (str): The record id of the search hit. + score (float): The similarity score of the returned record. + fields ({str: (bool, dict, float, int, list, str, none_type)}): The selected record fields associated with the search hit. + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.id = id + self.score = score + self.fields = fields + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/import_error_mode.py b/pinecone/core/openapi/db_data/model/import_error_mode.py index 0d92471fc..37dc94650 100644 --- a/pinecone/core/openapi/db_data/model/import_error_mode.py +++ b/pinecone/core/openapi/db_data/model/import_error_mode.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/import_model.py b/pinecone/core/openapi/db_data/model/import_model.py index 26544e209..9a6d06b1b 100644 --- a/pinecone/core/openapi/db_data/model/import_model.py +++ b/pinecone/core/openapi/db_data/model/import_model.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/index_description.py b/pinecone/core/openapi/db_data/model/index_description.py index 613d978ff..f2cec5cde 100644 --- a/pinecone/core/openapi/db_data/model/index_description.py +++ b/pinecone/core/openapi/db_data/model/index_description.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -90,6 +90,8 @@ def openapi_types(): "dimension": (int,), # noqa: E501 "index_fullness": (float,), # noqa: E501 "total_vector_count": (int,), # noqa: E501 + "metric": (str,), # noqa: E501 + "vector_type": (str,), # noqa: E501 } @cached_property @@ -101,6 +103,8 @@ def discriminator(): "dimension": "dimension", # noqa: E501 "index_fullness": "indexFullness", # noqa: E501 "total_vector_count": "totalVectorCount", # noqa: E501 + "metric": "metric", # noqa: E501 + "vector_type": "vectorType", # noqa: E501 } read_only_vars = {} @@ -144,9 +148,11 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 - dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + dimension (int): The dimension of the indexed vectors. Not specified if `sparse` index.. [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/2024-10/control-plane/describe_index).. [optional] # noqa: E501 total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 + metric (str): The metric used to measure similarity.. [optional] # noqa: E501 + vector_type (str): The type of vectors stored in the index.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -231,9 +237,11 @@ def __init__(self, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 - dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + dimension (int): The dimension of the indexed vectors. Not specified if `sparse` index.. [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/2024-10/control-plane/describe_index).. [optional] # noqa: E501 total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 + metric (str): The metric used to measure similarity.. [optional] # noqa: E501 + vector_type (str): The type of vectors stored in the index.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/db_data/model/list_imports_response.py b/pinecone/core/openapi/db_data/model/list_imports_response.py index 42af9c7d7..b1bb68b2e 100644 --- a/pinecone/core/openapi/db_data/model/list_imports_response.py +++ b/pinecone/core/openapi/db_data/model/list_imports_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/list_item.py b/pinecone/core/openapi/db_data/model/list_item.py index 1b6c813c3..0957ec95a 100644 --- a/pinecone/core/openapi/db_data/model/list_item.py +++ b/pinecone/core/openapi/db_data/model/list_item.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/list_response.py b/pinecone/core/openapi/db_data/model/list_response.py index 1f293889b..57227c29f 100644 --- a/pinecone/core/openapi/db_data/model/list_response.py +++ b/pinecone/core/openapi/db_data/model/list_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/namespace_summary.py b/pinecone/core/openapi/db_data/model/namespace_summary.py index fecc3ac6e..f9cb4699d 100644 --- a/pinecone/core/openapi/db_data/model/namespace_summary.py +++ b/pinecone/core/openapi/db_data/model/namespace_summary.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/pagination.py b/pinecone/core/openapi/db_data/model/pagination.py index 4bbd53ea5..cd19a79dd 100644 --- a/pinecone/core/openapi/db_data/model/pagination.py +++ b/pinecone/core/openapi/db_data/model/pagination.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/protobuf_any.py b/pinecone/core/openapi/db_data/model/protobuf_any.py index 927b0d94f..7b352868f 100644 --- a/pinecone/core/openapi/db_data/model/protobuf_any.py +++ b/pinecone/core/openapi/db_data/model/protobuf_any.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/protobuf_null_value.py b/pinecone/core/openapi/db_data/model/protobuf_null_value.py index 5b333dedb..86e180767 100644 --- a/pinecone/core/openapi/db_data/model/protobuf_null_value.py +++ b/pinecone/core/openapi/db_data/model/protobuf_null_value.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/query_request.py b/pinecone/core/openapi/db_data/model/query_request.py index 04c9f3b35..e3e551f2a 100644 --- a/pinecone/core/openapi/db_data/model/query_request.py +++ b/pinecone/core/openapi/db_data/model/query_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -164,7 +164,7 @@ def _from_openapi_data(cls, top_k, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata).. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata).. [optional] # noqa: E501 include_values (bool): Indicates whether vector values are included in the response.. [optional] if omitted the server will use the default value of False # noqa: E501 include_metadata (bool): Indicates whether metadata is included in the response as well as the ids.. [optional] if omitted the server will use the default value of False # noqa: E501 queries ([QueryVector]): DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.. [optional] # noqa: E501 @@ -259,7 +259,7 @@ def __init__(self, top_k, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata).. [optional] # noqa: E501 + filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata).. [optional] # noqa: E501 include_values (bool): Indicates whether vector values are included in the response.. [optional] if omitted the server will use the default value of False # noqa: E501 include_metadata (bool): Indicates whether metadata is included in the response as well as the ids.. [optional] if omitted the server will use the default value of False # noqa: E501 queries ([QueryVector]): DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.. [optional] # noqa: E501 diff --git a/pinecone/core/openapi/db_data/model/query_response.py b/pinecone/core/openapi/db_data/model/query_response.py index 39aa888cb..72febc1f9 100644 --- a/pinecone/core/openapi/db_data/model/query_response.py +++ b/pinecone/core/openapi/db_data/model/query_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/query_vector.py b/pinecone/core/openapi/db_data/model/query_vector.py index 4bc018390..d63412b02 100644 --- a/pinecone/core/openapi/db_data/model/query_vector.py +++ b/pinecone/core/openapi/db_data/model/query_vector.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/rpc_status.py b/pinecone/core/openapi/db_data/model/rpc_status.py index 021fd4f7c..25acb711b 100644 --- a/pinecone/core/openapi/db_data/model/rpc_status.py +++ b/pinecone/core/openapi/db_data/model/rpc_status.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/scored_vector.py b/pinecone/core/openapi/db_data/model/scored_vector.py index 5845dac9f..6fea349c5 100644 --- a/pinecone/core/openapi/db_data/model/scored_vector.py +++ b/pinecone/core/openapi/db_data/model/scored_vector.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/search_records_request.py b/pinecone/core/openapi/db_data/model/search_records_request.py new file mode 100644 index 000000000..22972fd92 --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_records_request.py @@ -0,0 +1,282 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.search_records_request_query import ( + SearchRecordsRequestQuery, + ) + from pinecone.core.openapi.db_data.model.search_records_request_rerank import ( + SearchRecordsRequestRerank, + ) + + globals()["SearchRecordsRequestQuery"] = SearchRecordsRequestQuery + globals()["SearchRecordsRequestRerank"] = SearchRecordsRequestRerank + + +class SearchRecordsRequest(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + validations = {("fields",): {}} + + @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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "query": (SearchRecordsRequestQuery,), # noqa: E501 + "fields": ([str],), # noqa: E501 + "rerank": (SearchRecordsRequestRerank,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "query": "query", # noqa: E501 + "fields": "fields", # noqa: E501 + "rerank": "rerank", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, query, *args, **kwargs): # noqa: E501 + """SearchRecordsRequest - a model defined in OpenAPI + + Args: + query (SearchRecordsRequestQuery): + + Keyword Args: + _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,) + fields ([str]): The fields to return in the search results.. [optional] # noqa: E501 + rerank (SearchRecordsRequestRerank): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.query = query + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, query, *args, **kwargs): # noqa: E501 + """SearchRecordsRequest - a model defined in OpenAPI + + Args: + query (SearchRecordsRequestQuery): + + Keyword Args: + _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,) + fields ([str]): The fields to return in the search results.. [optional] # noqa: E501 + rerank (SearchRecordsRequestRerank): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.query = query + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_records_request_query.py b/pinecone/core/openapi/db_data/model/search_records_request_query.py new file mode 100644 index 000000000..6fc5e815c --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_records_request_query.py @@ -0,0 +1,280 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.vector_values import VectorValues + + globals()["VectorValues"] = VectorValues + + +class SearchRecordsRequestQuery(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "top_k": (int,), # noqa: E501 + "filter": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "inputs": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + "vector": (VectorValues,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "top_k": "top_k", # noqa: E501 + "filter": "filter", # noqa: E501 + "inputs": "inputs", # noqa: E501 + "vector": "vector", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, top_k, *args, **kwargs): # noqa: E501 + """SearchRecordsRequestQuery - a model defined in OpenAPI + + Args: + top_k (int): The number of results to return for each search. + + Keyword Args: + _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,) + filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply.. [optional] # noqa: E501 + inputs ({str: (bool, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + vector (VectorValues): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.top_k = top_k + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, top_k, *args, **kwargs): # noqa: E501 + """SearchRecordsRequestQuery - a model defined in OpenAPI + + Args: + top_k (int): The number of results to return for each search. + + Keyword Args: + _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,) + filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply.. [optional] # noqa: E501 + inputs ({str: (bool, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + vector (VectorValues): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.top_k = top_k + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_records_request_rerank.py b/pinecone/core/openapi/db_data/model/search_records_request_rerank.py new file mode 100644 index 000000000..ec553243b --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_records_request_rerank.py @@ -0,0 +1,274 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class SearchRecordsRequestRerank(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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, 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 { + "model": (str,), # noqa: E501 + "rank_fields": ([str],), # noqa: E501 + "top_n": (int,), # noqa: E501 + "parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "model": "model", # noqa: E501 + "rank_fields": "rank_fields", # noqa: E501 + "top_n": "top_n", # noqa: E501 + "parameters": "parameters", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, model, rank_fields, *args, **kwargs): # noqa: E501 + """SearchRecordsRequestRerank - a model defined in OpenAPI + + Args: + model (str): The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. + rank_fields ([str]): The fields to use for reranking. + + Keyword Args: + _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,) + top_n (int): The number of top results to return after reranking. Defaults to top_k.. [optional] # noqa: E501 + parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.model = model + self.rank_fields = rank_fields + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, model, rank_fields, *args, **kwargs): # noqa: E501 + """SearchRecordsRequestRerank - a model defined in OpenAPI + + Args: + model (str): The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. + rank_fields ([str]): The fields to use for reranking. + + Keyword Args: + _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,) + top_n (int): The number of top results to return after reranking. Defaults to top_k.. [optional] # noqa: E501 + parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.model = model + self.rank_fields = rank_fields + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_records_response.py b/pinecone/core/openapi/db_data/model/search_records_response.py new file mode 100644 index 000000000..b4fd75b8b --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_records_response.py @@ -0,0 +1,278 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.search_records_response_result import ( + SearchRecordsResponseResult, + ) + from pinecone.core.openapi.db_data.model.search_usage import SearchUsage + + globals()["SearchRecordsResponseResult"] = SearchRecordsResponseResult + globals()["SearchUsage"] = SearchUsage + + +class SearchRecordsResponse(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "result": (SearchRecordsResponseResult,), # noqa: E501 + "usage": (SearchUsage,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "result": "result", # noqa: E501 + "usage": "usage", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, result, usage, *args, **kwargs): # noqa: E501 + """SearchRecordsResponse - a model defined in OpenAPI + + Args: + result (SearchRecordsResponseResult): + usage (SearchUsage): + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.result = result + self.usage = usage + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, result, usage, *args, **kwargs): # noqa: E501 + """SearchRecordsResponse - a model defined in OpenAPI + + Args: + result (SearchRecordsResponseResult): + usage (SearchUsage): + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.result = result + self.usage = usage + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_records_response_result.py b/pinecone/core/openapi/db_data/model/search_records_response_result.py new file mode 100644 index 000000000..1895cb4cb --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_records_response_result.py @@ -0,0 +1,268 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.hit import Hit + + globals()["Hit"] = Hit + + +class SearchRecordsResponseResult(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "hits": ([Hit],) # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "hits": "hits" # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, hits, *args, **kwargs): # noqa: E501 + """SearchRecordsResponseResult - a model defined in OpenAPI + + Args: + hits ([Hit]): The hits for the search document request. + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.hits = hits + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, hits, *args, **kwargs): # noqa: E501 + """SearchRecordsResponseResult - a model defined in OpenAPI + + Args: + hits ([Hit]): The hits for the search document request. + + Keyword Args: + _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,) + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.hits = hits + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_usage.py b/pinecone/core/openapi/db_data/model/search_usage.py new file mode 100644 index 000000000..dd88f79c0 --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_usage.py @@ -0,0 +1,272 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class SearchUsage(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + validations = { + ("read_units",): {"inclusive_minimum": 0}, + ("embed_total_tokens",): {"inclusive_minimum": 0}, + ("rerank_units",): {"inclusive_minimum": 0}, + } + + @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, 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 { + "read_units": (int,), # noqa: E501 + "embed_total_tokens": (int,), # noqa: E501 + "rerank_units": (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "read_units": "read_units", # noqa: E501 + "embed_total_tokens": "embed_total_tokens", # noqa: E501 + "rerank_units": "rerank_units", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, read_units, *args, **kwargs): # noqa: E501 + """SearchUsage - a model defined in OpenAPI + + Args: + read_units (int): The number of read units consumed by this operation. + + Keyword Args: + _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,) + embed_total_tokens (int): The number of embedding tokens consumed by this operation.. [optional] # noqa: E501 + rerank_units (int): The number of rerank units consumed by this operation.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.read_units = read_units + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, read_units, *args, **kwargs): # noqa: E501 + """SearchUsage - a model defined in OpenAPI + + Args: + read_units (int): The number of read units consumed by this operation. + + Keyword Args: + _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,) + embed_total_tokens (int): The number of embedding tokens consumed by this operation.. [optional] # noqa: E501 + rerank_units (int): The number of rerank units consumed by this operation.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.read_units = read_units + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/search_vector.py b/pinecone/core/openapi/db_data/model/search_vector.py new file mode 100644 index 000000000..49932c8f7 --- /dev/null +++ b/pinecone/core/openapi/db_data/model/search_vector.py @@ -0,0 +1,262 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.vector_values import VectorValues + + globals()["VectorValues"] = VectorValues + + +class SearchVector(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "values": (VectorValues,) # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "values": "values" # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SearchVector - a model defined in OpenAPI + + Keyword Args: + _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,) + values (VectorValues): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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): # noqa: E501 + """SearchVector - a model defined in OpenAPI + + Keyword Args: + _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,) + values (VectorValues): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/single_query_results.py b/pinecone/core/openapi/db_data/model/single_query_results.py index 8b80f10dd..2ca4548a9 100644 --- a/pinecone/core/openapi/db_data/model/single_query_results.py +++ b/pinecone/core/openapi/db_data/model/single_query_results.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/sparse_values.py b/pinecone/core/openapi/db_data/model/sparse_values.py index 95e33dfed..7adeb8322 100644 --- a/pinecone/core/openapi/db_data/model/sparse_values.py +++ b/pinecone/core/openapi/db_data/model/sparse_values.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/start_import_request.py b/pinecone/core/openapi/db_data/model/start_import_request.py index db2a25b56..71750d91a 100644 --- a/pinecone/core/openapi/db_data/model/start_import_request.py +++ b/pinecone/core/openapi/db_data/model/start_import_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/start_import_response.py b/pinecone/core/openapi/db_data/model/start_import_response.py index a32af8ad7..371ddd4c4 100644 --- a/pinecone/core/openapi/db_data/model/start_import_response.py +++ b/pinecone/core/openapi/db_data/model/start_import_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/update_request.py b/pinecone/core/openapi/db_data/model/update_request.py index 2f4f1f793..dbb2b482e 100644 --- a/pinecone/core/openapi/db_data/model/update_request.py +++ b/pinecone/core/openapi/db_data/model/update_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/upsert_record.py b/pinecone/core/openapi/db_data/model/upsert_record.py new file mode 100644 index 000000000..212bfce1e --- /dev/null +++ b/pinecone/core/openapi/db_data/model/upsert_record.py @@ -0,0 +1,278 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.openapi.db_data.model.upsert_record_embed import UpsertRecordEmbed + from pinecone.core.openapi.db_data.model.vector import Vector + + globals()["UpsertRecordEmbed"] = UpsertRecordEmbed + globals()["Vector"] = Vector + + +class UpsertRecord(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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 + """ + lazy_import() + return (bool, 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. + """ + lazy_import() + return { + "id": (str,), # noqa: E501 + "vector": (Vector,), # noqa: E501 + "embed": (UpsertRecordEmbed,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "id": "_id", # noqa: E501 + "vector": "_vector", # noqa: E501 + "embed": "_embed", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 + """UpsertRecord - a model defined in OpenAPI + + Args: + id (str): The unique ID of the record to upsert. + + Keyword Args: + _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,) + vector (Vector): [optional] # noqa: E501 + embed (UpsertRecordEmbed): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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.id = id + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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, id, *args, **kwargs): # noqa: E501 + """UpsertRecord - a model defined in OpenAPI + + Args: + id (str): The unique ID of the record to upsert. + + Keyword Args: + _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,) + vector (Vector): [optional] # noqa: E501 + embed (UpsertRecordEmbed): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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.id = id + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/upsert_record_embed.py b/pinecone/core/openapi/db_data/model/upsert_record_embed.py new file mode 100644 index 000000000..53bc7bfde --- /dev/null +++ b/pinecone/core/openapi/db_data/model/upsert_record_embed.py @@ -0,0 +1,254 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class UpsertRecordEmbed(ModelNormal): + """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. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + 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 = {} + + 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, 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 { + "inputs": ({str: (bool, dict, float, int, list, str, none_type)},) # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "inputs": "inputs" # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """UpsertRecordEmbed - a model defined in OpenAPI + + Keyword Args: + _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,) + inputs ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + 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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + 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): # noqa: E501 + """UpsertRecordEmbed - a model defined in OpenAPI + + Keyword Args: + _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,) + inputs ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _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__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise PineconeApiAttributeError( + f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes." + ) diff --git a/pinecone/core/openapi/db_data/model/upsert_request.py b/pinecone/core/openapi/db_data/model/upsert_request.py index 034307554..35d0eefd2 100644 --- a/pinecone/core/openapi/db_data/model/upsert_request.py +++ b/pinecone/core/openapi/db_data/model/upsert_request.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/upsert_response.py b/pinecone/core/openapi/db_data/model/upsert_response.py index ff2797535..c65809de3 100644 --- a/pinecone/core/openapi/db_data/model/upsert_response.py +++ b/pinecone/core/openapi/db_data/model/upsert_response.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/usage.py b/pinecone/core/openapi/db_data/model/usage.py index 5316e10fd..0a3d465d1 100644 --- a/pinecone/core/openapi/db_data/model/usage.py +++ b/pinecone/core/openapi/db_data/model/usage.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/vector.py b/pinecone/core/openapi/db_data/model/vector.py index 6dc857467..0c69db494 100644 --- a/pinecone/core/openapi/db_data/model/vector.py +++ b/pinecone/core/openapi/db_data/model/vector.py @@ -3,7 +3,7 @@ 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-10 +The version of the OpenAPI document: 2025-01 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/openapi/db_data/model/vector_values.py b/pinecone/core/openapi/db_data/model/vector_values.py new file mode 100644 index 000000000..5ad43f206 --- /dev/null +++ b/pinecone/core/openapi/db_data/model/vector_values.py @@ -0,0 +1,272 @@ +""" +Pinecone Data 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: 2025-01 +Contact: support@pinecone.io +Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel +from pinecone.openapi_support.exceptions import PineconeApiAttributeError + + +class VectorValues(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 = {} + + validations = {("value",): {}} + + @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, 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": ([float],)} + + @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): + """VectorValues - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([float]): This is the vector data included in the request.. # noqa: E501 + + Keyword Args: + value ([float]): This is the vector data included in the request.. # 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: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _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): + """VectorValues - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([float]): This is the vector data included in the request.. # noqa: E501 + + Keyword Args: + value ([float]): This is the vector data included in the request.. # 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: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _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/db_data/models/__init__.py b/pinecone/core/openapi/db_data/models/__init__.py index 14e62170b..ce76fd856 100644 --- a/pinecone/core/openapi/db_data/models/__init__.py +++ b/pinecone/core/openapi/db_data/models/__init__.py @@ -14,6 +14,7 @@ DescribeIndexStatsRequest, ) from pinecone.core.openapi.db_data.model.fetch_response import FetchResponse +from pinecone.core.openapi.db_data.model.hit import Hit from pinecone.core.openapi.db_data.model.import_error_mode import ImportErrorMode from pinecone.core.openapi.db_data.model.import_model import ImportModel from pinecone.core.openapi.db_data.model.index_description import IndexDescription @@ -29,12 +30,28 @@ from pinecone.core.openapi.db_data.model.query_vector import QueryVector from pinecone.core.openapi.db_data.model.rpc_status import RpcStatus from pinecone.core.openapi.db_data.model.scored_vector import ScoredVector +from pinecone.core.openapi.db_data.model.search_records_request import SearchRecordsRequest +from pinecone.core.openapi.db_data.model.search_records_request_query import ( + SearchRecordsRequestQuery, +) +from pinecone.core.openapi.db_data.model.search_records_request_rerank import ( + SearchRecordsRequestRerank, +) +from pinecone.core.openapi.db_data.model.search_records_response import SearchRecordsResponse +from pinecone.core.openapi.db_data.model.search_records_response_result import ( + SearchRecordsResponseResult, +) +from pinecone.core.openapi.db_data.model.search_usage import SearchUsage +from pinecone.core.openapi.db_data.model.search_vector import SearchVector from pinecone.core.openapi.db_data.model.single_query_results import SingleQueryResults from pinecone.core.openapi.db_data.model.sparse_values import SparseValues from pinecone.core.openapi.db_data.model.start_import_request import StartImportRequest from pinecone.core.openapi.db_data.model.start_import_response import StartImportResponse from pinecone.core.openapi.db_data.model.update_request import UpdateRequest +from pinecone.core.openapi.db_data.model.upsert_record import UpsertRecord +from pinecone.core.openapi.db_data.model.upsert_record_embed import UpsertRecordEmbed from pinecone.core.openapi.db_data.model.upsert_request import UpsertRequest from pinecone.core.openapi.db_data.model.upsert_response import UpsertResponse from pinecone.core.openapi.db_data.model.usage import Usage from pinecone.core.openapi.db_data.model.vector import Vector +from pinecone.core.openapi.db_data.model.vector_values import VectorValues diff --git a/tests/unit/openapi_support/test_api_client.py b/tests/unit/openapi_support/test_api_client.py index eb69f2e33..3b46914b5 100644 --- a/tests/unit/openapi_support/test_api_client.py +++ b/tests/unit/openapi_support/test_api_client.py @@ -61,9 +61,11 @@ def test_sanitize_for_serialization_serializes_model_normal(self): m = IndexModel( name="myindex", dimension=10, + metric="cosine", host="localhost", spec=IndexModelSpec(), status=IndexModelStatus(ready=True, state="Ready"), + vector_type="dense", ) assert ApiClient.sanitize_for_serialization(m) == { "name": "myindex", @@ -72,6 +74,26 @@ def test_sanitize_for_serialization_serializes_model_normal(self): "host": "localhost", "spec": {}, "status": {"ready": True, "state": "Ready"}, + "vector_type": "dense", + } + + m2 = IndexModel( + name="myindex2", + metric="cosine", + host="localhost", + spec=IndexModelSpec(), + status=IndexModelStatus(ready=True, state="Ready"), + vector_type="sparse", + deletion_protection=DeletionProtection(value="enabled"), + ) + assert ApiClient.sanitize_for_serialization(m2) == { + "name": "myindex2", + "metric": "cosine", + "host": "localhost", + "spec": {}, + "status": {"ready": True, "state": "Ready"}, + "vector_type": "sparse", + "deletion_protection": "enabled", } def test_sanitize_for_serialization_serializes_model_simple(self): From 1571e16d92b63eff3c14e5a726b67aa8f8b76020 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Thu, 5 Dec 2024 12:04:34 -0500 Subject: [PATCH 02/21] Control plane docs extraction --- pinecone/control/pinecone.py | 473 +-------------------- pinecone/control/pinecone_interface.py | 549 +++++++++++++++++++++++++ 2 files changed, 559 insertions(+), 463 deletions(-) create mode 100644 pinecone/control/pinecone_interface.py diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 2216986f9..4d6d27a46 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -3,6 +3,7 @@ from typing import Optional, Dict, Any, Union, List, Tuple, Literal from .index_host_store import IndexHostStore +from .pinecone_interface import PineconeDBControlInterface from pinecone.config import PineconeConfig, Config, ConfigBuilder @@ -32,9 +33,17 @@ from pinecone_plugin_interface import load_and_install as install_plugins logger = logging.getLogger(__name__) +""" @private """ -class Pinecone: +class Pinecone(PineconeDBControlInterface): + """ + A client for interacting with Pinecone's vector database. + + This class implements methods for managing and interacting with Pinecone resources + such as collections and indexes. + """ + def __init__( self, api_key: Optional[str] = None, @@ -49,147 +58,6 @@ def __init__( index_api: Optional[ManageIndexesApi] = None, **kwargs, ): - """ - The `Pinecone` class is the main entry point for interacting with Pinecone via this Python SDK. - It is used to create, delete, and manage your indexes and collections. - - :param api_key: The API key to use for authentication. If not passed via kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - :type api_key: str, optional - :param host: The control plane host to connect to. - :type host: str, optional - :param proxy_url: The URL of the proxy to use for the connection. Default: `None` - :type proxy_url: str, optional - :param proxy_headers: Additional headers to pass to the proxy. Use this if your proxy setup requires authentication. Default: `{}` - :type proxy_headers: Dict[str, str], optional - :param ssl_ca_certs: The path to the SSL CA certificate bundle to use for the connection. This path should point to a file in PEM format. Default: `None` - :type ssl_ca_certs: str, optional - :param ssl_verify: SSL verification is performed by default, but can be disabled using the boolean flag. Default: `True` - :type ssl_verify: bool, optional - :param config: A `pinecone.config.Config` object. If passed, the `api_key` and `host` parameters will be ignored. - :type config: pinecone.config.Config, optional - :param additional_headers: Additional headers to pass to the API. Default: `{}` - :type additional_headers: Dict[str, str], optional - :param pool_threads: The number of threads to use for the connection pool. Default: `1` - :type pool_threads: int, optional - :param index_api: An instance of `pinecone.core.client.api.manage_indexes_api.ManageIndexesApi`. If passed, the `host` parameter will be ignored. - :type index_api: pinecone.core.client.api.manage_indexes_api.ManageIndexesApi, optional - - - ### Configuration with environment variables - - If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - ``` - - ### Configuration with keyword arguments - - If you prefer being more explicit in your code, you can also pass the API as a keyword argument. - - ```python - import os - from pinecone import Pinecone - - pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) - ``` - - ### Environment variables - - The Pinecone client supports the following environment variables: - - - `PINECONE_API_KEY`: The API key to use for authentication. If not passed via - kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - - - `PINECONE_DEBUG_CURL`: When troubleshooting it can be very useful to run curl - commands against the control plane API to see exactly what data is being sent - and received without all the abstractions and transformations applied by the Python - SDK. If you set this environment variable to `true`, the Pinecone client will use - request parameters to print out an equivalent curl command that you can run yourself - or share with Pinecone support. **Be very careful with this option, as it will print out - your API key** which forms part of a required authentication header. Default: `false` - - ### Proxy configuration - - If your network setup requires you to interact with Pinecone via a proxy, you will need - to pass additional configuration using optional keyword parameters. These optional parameters - are forwarded to `urllib3`, which is the underlying library currently used by the Pinecone client to - make HTTP requests. You may find it helpful to refer to the - [urllib3 documentation on working with proxies](https://urllib3.readthedocs.io/en/stable/advanced-usage.html#http-and-https-proxies) - while troubleshooting these settings. - - Here is a basic example: - - ```python - from pinecone import Pinecone - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com' - ) - - pc.list_indexes() - ``` - - If your proxy requires authentication, you can pass those values in a header dictionary using the `proxy_headers` parameter. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password') - ) - - pc.list_indexes() - ``` - - ### Using proxies with self-signed certificates - - By default the Pinecone Python client will perform SSL certificate verification - using the CA bundle maintained by Mozilla in the [certifi](https://pypi.org/project/certifi/) package. - If your proxy server is using a self-signed certificate, you will need to pass the path to the certificate - in PEM format using the `ssl_ca_certs` parameter. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password'), - ssl_ca_certs='path/to/cert-bundle.pem' - ) - - pc.list_indexes() - ``` - - ### Disabling SSL verification - - If you would like to disable SSL verification, you can pass the `ssl_verify` - parameter with a value of `False`. We do not recommend going to production with SSL verification disabled. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password'), - ssl_ca_certs='path/to/cert-bundle.pem', - ssl_verify=False - ) - - pc.list_indexes() - - ``` - """ if config: if not isinstance(config, Config): raise TypeError("config must be of type pinecone.config.Config") @@ -256,65 +124,6 @@ def create_index( timeout: Optional[int] = None, deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", ): - """Creates a Pinecone index. - - :param name: The name of the index to create. Must be unique within your project and - cannot be changed once created. Allowed characters are lowercase letters, numbers, - and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. - :type name: str - :param dimension: The dimension of vectors that will be inserted in the index. This should - match the dimension of the embeddings you will be inserting. For example, if you are using - OpenAI's CLIP model, you should use `dimension=1536`. - :type dimension: int - :param metric: Type of metric used in the vector index when querying, one of `{"cosine", "dotproduct", "euclidean"}`. Defaults to `"cosine"`. - Defaults to `"cosine"`. - :type metric: str, optional - :param spec: A dictionary containing configurations describing how the index should be deployed. For serverless indexes, - specify region and cloud. For pod indexes, specify replicas, shards, pods, pod_type, metadata_config, and source_collection. - :type spec: Dict - :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 - - ```python - import os - from pinecone import Pinecone, ServerlessSpec - - client = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) - - client.create_index( - name="my_index", - dimension=1536, - metric="cosine", - spec=ServerlessSpec(cloud="aws", region="us-west-2"), - deletion_protection="enabled" - ) - ``` - - ### Creating a pod index - - ```python - import os - from pinecone import Pinecone, PodSpec - - client = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) - - client.create_index( - name="my_index", - dimension=1536, - metric="cosine", - spec=PodSpec( - environment="us-east1-gcp", - pod_type="p1.x1" - ), - deletion_protection="enabled" - ) - ``` - """ - api_instance = self.index_api def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: @@ -404,24 +213,6 @@ def is_ready(): ) def delete_index(self, name: str, timeout: Optional[int] = None): - """Deletes a Pinecone index. - - Deleting an index is an irreversible operation. All data in the index will be lost. - When you use this command, a request is sent to the Pinecone control plane to delete - the index, but the termination is not synchronous because resources take a few moments to - be released. - - You can check the status of the index by calling the `describe_index()` command. - With repeated polling of the describe_index command, you will see the index transition to a - `Terminating` state before eventually resulting in a 404 after it has been removed. - - :param name: the name of the index. - :type name: str - :param timeout: Number of seconds to poll status checking whether the index has been deleted. If None, - wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. Default: None - :type timeout: int, optional - """ api_instance = self.index_api api_instance.delete_index(name) self.index_host_store.delete_host(self.config, name) @@ -449,83 +240,10 @@ def get_remaining(): ) def list_indexes(self) -> IndexList: - """Lists all indexes. - - The results include a description of all indexes in your project, including the - index name, dimension, metric, status, and spec. - - :return: Returns an `IndexList` object, which is iterable and contains a - list of `IndexModel` objects. It also has a convenience method `names()` - which returns a list of index names. - - ```python - from pinecone import Pinecone - - client = Pinecone() - - index_name = "my_index" - if index_name not in client.list_indexes().names(): - print("Index does not exist, creating...") - client.create_index( - name=index_name, - dimension=768, - metric="cosine", - spec=ServerlessSpec(cloud="aws", region="us-west-2") - ) - ``` - - You can also use the `list_indexes()` method to iterate over all indexes in your project - and get other information besides just names. - - ```python - from pinecone import Pinecone - - client = Pinecone() - - for index in client.list_indexes(): - print(index.name) - print(index.dimension) - print(index.metric) - print(index.status) - print(index.host) - print(index.spec) - ``` - - """ response = self.index_api.list_indexes() return IndexList(response) def describe_index(self, name: str): - """Describes a Pinecone index. - - :param name: the name of the index to describe. - :return: Returns an `IndexModel` object - which gives access to properties such as the - index name, dimension, metric, host url, status, - and spec. - - ### Getting your index host url - - In a real production situation, you probably want to - store the host url in an environment variable so you - don't have to call describe_index and re-fetch it - every time you want to use the index. But this example - shows how to get the value from the API using describe_index. - - ```python - from pinecone import Pinecone, Index - - client = Pinecone() - - description = client.describe_index("my_index") - - host = description.host - print(f"Your index is hosted at {description.host}") - - index = client.Index(name="my_index", host=host) - index.upsert(vectors=[...]) - ``` - """ api_instance = self.index_api description = api_instance.describe_index(name) host = description.host @@ -534,27 +252,6 @@ def describe_index(self, name: str): return IndexModel(description) def has_index(self, name: str) -> bool: - """Checks if a Pinecone index exists. - - :param name: The name of the index to check for existence. - :return: Returns `True` if the index exists, `False` otherwise. - - ### Example Usage - - ```python - import os - from pinecone import Pinecone - - api_key = os.environ.get("PINECONE_API_KEY") - pc = Pinecone(api_key=api_key) - - if pc.has_index("my_index_name"): - print("The index exists") - else: - print("The index does not exist") - ``` - """ - if name in self.list_indexes().names(): return True else: @@ -567,28 +264,6 @@ def configure_index( 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. - - :param: name: the name of the Index - :param: replicas: the desired number of replicas, lowest value is 0. - :param: pod_type: the new pod_type for the index. To learn more about the - available pod types, please see [Understanding Indexes](https://docs.pinecone.io/docs/indexes) - - - ```python - from pinecone import Pinecone - - client = Pinecone() - - # Make a configuration change - client.configure_index(name="my_index", replicas=4) - - # Call describe_index to see the index status as the - # change is applied. - client.describe_index("my_index") - ``` - - """ api_instance = self.index_api if deletion_protection is None: @@ -614,72 +289,21 @@ def configure_index( 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 - - :param name: Name of the collection - :param source: Name of the source index - """ api_instance = self.index_api api_instance.create_collection( create_collection_request=CreateCollectionRequest(name=name, source=source) ) def list_collections(self) -> CollectionList: - """List all collections - - ```python - from pinecone import Pinecone - - client = Pinecone() - - for collection in client.list_collections(): - print(collection.name) - print(collection.source) - - # You can also iterate specifically over the collection - # names with the .names() helper. - collection_name="my_collection" - for collection_name in client.list_collections().names(): - print(collection_name) - ``` - """ api_instance = self.index_api response = api_instance.list_collections() return CollectionList(response) def delete_collection(self, name: str): - """Deletes a collection. - - :param: name: The name of the collection - - Deleting a collection is an irreversible operation. All data - in the collection will be lost. - - This method tells Pinecone you would like to delete a collection, - but it takes a few moments to complete the operation. Use the - `describe_collection()` method to confirm that the collection - has been deleted. - """ api_instance = self.index_api api_instance.delete_collection(name) def describe_collection(self, name: str): - """Describes a collection. - :param: The name of the collection - :return: Description of the collection - - ```python - from pinecone import Pinecone - - client = Pinecone() - - description = client.describe_collection("my_collection") - print(description.name) - print(description.source) - print(description.status) - print(description.size) - ``` - """ api_instance = self.index_api return api_instance.describe_collection(name).to_dict() @@ -697,83 +321,6 @@ def from_documents(*args, **kwargs): raise AttributeError(_build_langchain_attribute_error_message("from_documents")) def Index(self, name: str = "", host: str = "", **kwargs): - """ - Target an index for data operations. - - ### Target an index by host url - - In production situations, you want to uspert or query your data as quickly - as possible. If you know in advance the host url of your index, you can - eliminate a round trip to the Pinecone control plane by specifying the - host of the index. - - ```python - import os - from pinecone import Pinecone - - api_key = os.environ.get("PINECONE_API_KEY") - index_host = os.environ.get("PINECONE_INDEX_HOST") - - pc = Pinecone(api_key=api_key) - index = pc.Index(host=index_host) - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - - To find your host url, you can use the Pinecone control plane to describe - the index. The host url is returned in the response. Or, alternatively, the - host is displayed in the Pinecone web console. - - ```python - import os - from pinecone import Pinecone - - pc = Pinecone( - api_key=os.environ.get("PINECONE_API_KEY") - ) - - host = pc.describe_index('index-name').host - ``` - - ### Target an index by name (not recommended for production) - - For more casual usage, such as when you are playing and exploring with Pinecone - in a notebook setting, you can also target an index by name. If you use this - approach, the client may need to perform an extra call to the Pinecone control - plane to get the host url on your behalf to get the index host. - - The client will cache the index host for future use whenever it is seen, so you - will only incur the overhead of only one call. But this approach is not - recommended for production usage. - - ```python - import os - from pinecone import Pinecone, ServerlessSpec - - api_key = os.environ.get("PINECONE_API_KEY") - - pc = Pinecone(api_key=api_key) - pc.create_index( - name='my_index', - dimension=1536, - metric='cosine', - spec=ServerlessSpec(cloud='aws', region='us-west-2') - ) - index = pc.Index('my_index') - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - - Arguments: - name: The name of the index to target. If you specify the name of the index, the client will - fetch the host url from the Pinecone control plane. - host: The host url of the index to target. If you specify the host url, the client will use - the host url directly without making any additional calls to the control plane. - pool_threads: The number of threads to use when making parallel requests by calling index methods with optional kwarg async_req=True, or using methods that make use of parallelism automatically such as query_namespaces(). Default: 1 - connection_pool_maxsize: The maximum number of connections to keep in the connection pool. Default: 5 * multiprocessing.cpu_count() - """ if name == "" and host == "": raise ValueError("Either name or host must be specified") diff --git a/pinecone/control/pinecone_interface.py b/pinecone/control/pinecone_interface.py new file mode 100644 index 000000000..2780d6b23 --- /dev/null +++ b/pinecone/control/pinecone_interface.py @@ -0,0 +1,549 @@ +from abc import ABC, abstractmethod + +from typing import Optional, Dict, Union, Literal + + +from pinecone.config import Config + +from pinecone.core.openapi.db_control.api.manage_indexes_api import ManageIndexesApi + + +from pinecone.models import ServerlessSpec, PodSpec, IndexList, CollectionList + + +class PineconeDBControlInterface(ABC): + @abstractmethod + def __init__( + self, + api_key: Optional[str] = None, + host: Optional[str] = None, + proxy_url: Optional[str] = None, + proxy_headers: Optional[Dict[str, str]] = None, + ssl_ca_certs: Optional[str] = None, + ssl_verify: Optional[bool] = None, + config: Optional[Config] = None, + additional_headers: Optional[Dict[str, str]] = {}, + pool_threads: Optional[int] = 1, + index_api: Optional[ManageIndexesApi] = None, + **kwargs, + ): + """ + The `Pinecone` class is the main entry point for interacting with Pinecone via this Python SDK. + It is used to create, delete, and manage your indexes and collections. + + :param api_key: The API key to use for authentication. If not passed via kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. + :type api_key: str, optional + :param host: The control plane host to connect to. + :type host: str, optional + :param proxy_url: The URL of the proxy to use for the connection. Default: `None` + :type proxy_url: str, optional + :param proxy_headers: Additional headers to pass to the proxy. Use this if your proxy setup requires authentication. Default: `{}` + :type proxy_headers: Dict[str, str], optional + :param ssl_ca_certs: The path to the SSL CA certificate bundle to use for the connection. This path should point to a file in PEM format. Default: `None` + :type ssl_ca_certs: str, optional + :param ssl_verify: SSL verification is performed by default, but can be disabled using the boolean flag. Default: `True` + :type ssl_verify: bool, optional + :param config: A `pinecone.config.Config` object. If passed, the `api_key` and `host` parameters will be ignored. + :type config: pinecone.config.Config, optional + :param additional_headers: Additional headers to pass to the API. Default: `{}` + :type additional_headers: Dict[str, str], optional + :param pool_threads: The number of threads to use for the connection pool. Default: `1` + :type pool_threads: int, optional + :param index_api: An instance of `pinecone.core.client.api.manage_indexes_api.ManageIndexesApi`. If passed, the `host` parameter will be ignored. + :type index_api: pinecone.core.client.api.manage_indexes_api.ManageIndexesApi, optional + + + ### Configuration with environment variables + + If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. + + ```python + from pinecone import Pinecone + + pc = Pinecone() + ``` + + ### Configuration with keyword arguments + + If you prefer being more explicit in your code, you can also pass the API as a keyword argument. + + ```python + import os + from pinecone import Pinecone + + pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) + ``` + + ### Environment variables + + The Pinecone client supports the following environment variables: + + - `PINECONE_API_KEY`: The API key to use for authentication. If not passed via + kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. + + - `PINECONE_DEBUG_CURL`: When troubleshooting it can be very useful to run curl + commands against the control plane API to see exactly what data is being sent + and received without all the abstractions and transformations applied by the Python + SDK. If you set this environment variable to `true`, the Pinecone client will use + request parameters to print out an equivalent curl command that you can run yourself + or share with Pinecone support. **Be very careful with this option, as it will print out + your API key** which forms part of a required authentication header. Default: `false` + + ### Proxy configuration + + If your network setup requires you to interact with Pinecone via a proxy, you will need + to pass additional configuration using optional keyword parameters. These optional parameters + are forwarded to `urllib3`, which is the underlying library currently used by the Pinecone client to + make HTTP requests. You may find it helpful to refer to the + [urllib3 documentation on working with proxies](https://urllib3.readthedocs.io/en/stable/advanced-usage.html#http-and-https-proxies) + while troubleshooting these settings. + + Here is a basic example: + + ```python + from pinecone import Pinecone + + pc = Pinecone( + api_key='YOUR_API_KEY', + proxy_url='https://your-proxy.com' + ) + + pc.list_indexes() + ``` + + If your proxy requires authentication, you can pass those values in a header dictionary using the `proxy_headers` parameter. + + ```python + from pinecone import Pinecone + import urllib3 import make_headers + + pc = Pinecone( + api_key='YOUR_API_KEY', + proxy_url='https://your-proxy.com', + proxy_headers=make_headers(proxy_basic_auth='username:password') + ) + + pc.list_indexes() + ``` + + ### Using proxies with self-signed certificates + + By default the Pinecone Python client will perform SSL certificate verification + using the CA bundle maintained by Mozilla in the [certifi](https://pypi.org/project/certifi/) package. + If your proxy server is using a self-signed certificate, you will need to pass the path to the certificate + in PEM format using the `ssl_ca_certs` parameter. + + ```python + from pinecone import Pinecone + import urllib3 import make_headers + + pc = Pinecone( + api_key='YOUR_API_KEY', + proxy_url='https://your-proxy.com', + proxy_headers=make_headers(proxy_basic_auth='username:password'), + ssl_ca_certs='path/to/cert-bundle.pem' + ) + + pc.list_indexes() + ``` + + ### Disabling SSL verification + + If you would like to disable SSL verification, you can pass the `ssl_verify` + parameter with a value of `False`. We do not recommend going to production with SSL verification disabled. + + ```python + from pinecone import Pinecone + import urllib3 import make_headers + + pc = Pinecone( + api_key='YOUR_API_KEY', + proxy_url='https://your-proxy.com', + proxy_headers=make_headers(proxy_basic_auth='username:password'), + ssl_ca_certs='path/to/cert-bundle.pem', + ssl_verify=False + ) + + pc.list_indexes() + + ``` + """ + + pass + + @abstractmethod + def create_index( + self, + name: str, + dimension: int, + spec: Union[Dict, ServerlessSpec, PodSpec], + metric: Optional[str] = "cosine", + timeout: Optional[int] = None, + deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", + ): + """Creates a Pinecone index. + + :param name: The name of the index to create. Must be unique within your project and + cannot be changed once created. Allowed characters are lowercase letters, numbers, + and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. + :type name: str + :param dimension: The dimension of vectors that will be inserted in the index. This should + match the dimension of the embeddings you will be inserting. For example, if you are using + OpenAI's CLIP model, you should use `dimension=1536`. + :type dimension: int + :param metric: Type of metric used in the vector index when querying, one of `{"cosine", "dotproduct", "euclidean"}`. Defaults to `"cosine"`. + Defaults to `"cosine"`. + :type metric: str, optional + :param spec: A dictionary containing configurations describing how the index should be deployed. For serverless indexes, + specify region and cloud. For pod indexes, specify replicas, shards, pods, pod_type, metadata_config, and source_collection. + :type spec: Dict + :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 + + ```python + import os + from pinecone import Pinecone, ServerlessSpec + + client = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) + + client.create_index( + name="my_index", + dimension=1536, + metric="cosine", + spec=ServerlessSpec(cloud="aws", region="us-west-2"), + deletion_protection="enabled" + ) + ``` + + ### Creating a pod index + + ```python + import os + from pinecone import Pinecone, PodSpec + + client = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) + + client.create_index( + name="my_index", + dimension=1536, + metric="cosine", + spec=PodSpec( + environment="us-east1-gcp", + pod_type="p1.x1" + ), + deletion_protection="enabled" + ) + ``` + """ + pass + + @abstractmethod + def delete_index(self, name: str, timeout: Optional[int] = None): + """Deletes a Pinecone index. + + Deleting an index is an irreversible operation. All data in the index will be lost. + When you use this command, a request is sent to the Pinecone control plane to delete + the index, but the termination is not synchronous because resources take a few moments to + be released. + + You can check the status of the index by calling the `describe_index()` command. + With repeated polling of the describe_index command, you will see the index transition to a + `Terminating` state before eventually resulting in a 404 after it has been removed. + + :param name: the name of the index. + :type name: str + :param timeout: Number of seconds to poll status checking whether the index has been deleted. If None, + wait indefinitely; if >=0, time out after this many seconds; + if -1, return immediately and do not wait. Default: None + :type timeout: int, optional + """ + pass + + @abstractmethod + def list_indexes(self) -> IndexList: + """Lists all indexes. + + The results include a description of all indexes in your project, including the + index name, dimension, metric, status, and spec. + + :return: Returns an `IndexList` object, which is iterable and contains a + list of `IndexModel` objects. It also has a convenience method `names()` + which returns a list of index names. + + ```python + from pinecone import Pinecone + + client = Pinecone() + + index_name = "my_index" + if index_name not in client.list_indexes().names(): + print("Index does not exist, creating...") + client.create_index( + name=index_name, + dimension=768, + metric="cosine", + spec=ServerlessSpec(cloud="aws", region="us-west-2") + ) + ``` + + You can also use the `list_indexes()` method to iterate over all indexes in your project + and get other information besides just names. + + ```python + from pinecone import Pinecone + + client = Pinecone() + + for index in client.list_indexes(): + print(index.name) + print(index.dimension) + print(index.metric) + print(index.status) + print(index.host) + print(index.spec) + ``` + + """ + pass + + @abstractmethod + def describe_index(self, name: str): + """Describes a Pinecone index. + + :param name: the name of the index to describe. + :return: Returns an `IndexModel` object + which gives access to properties such as the + index name, dimension, metric, host url, status, + and spec. + + ### Getting your index host url + + In a real production situation, you probably want to + store the host url in an environment variable so you + don't have to call describe_index and re-fetch it + every time you want to use the index. But this example + shows how to get the value from the API using describe_index. + + ```python + from pinecone import Pinecone, Index + + client = Pinecone() + + description = client.describe_index("my_index") + + host = description.host + print(f"Your index is hosted at {description.host}") + + index = client.Index(name="my_index", host=host) + index.upsert(vectors=[...]) + ``` + """ + pass + + @abstractmethod + def has_index(self, name: str) -> bool: + """Checks if a Pinecone index exists. + + :param name: The name of the index to check for existence. + :return: Returns `True` if the index exists, `False` otherwise. + + ### Example Usage + + ```python + import os + from pinecone import Pinecone + + api_key = os.environ.get("PINECONE_API_KEY") + pc = Pinecone(api_key=api_key) + + if pc.has_index("my_index_name"): + print("The index exists") + else: + print("The index does not exist") + ``` + """ + pass + + @abstractmethod + 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. + + :param: name: the name of the Index + :param: replicas: the desired number of replicas, lowest value is 0. + :param: pod_type: the new pod_type for the index. To learn more about the + available pod types, please see [Understanding Indexes](https://docs.pinecone.io/docs/indexes) + + + ```python + from pinecone import Pinecone + + client = Pinecone() + + # Make a configuration change + client.configure_index(name="my_index", replicas=4) + + # Call describe_index to see the index status as the + # change is applied. + client.describe_index("my_index") + ``` + + """ + pass + + @abstractmethod + def create_collection(self, name: str, source: str): + """Create a collection from a pod-based index + + :param name: Name of the collection + :param source: Name of the source index + """ + pass + + @abstractmethod + def list_collections(self) -> CollectionList: + """List all collections + + ```python + from pinecone import Pinecone + + client = Pinecone() + + for collection in client.list_collections(): + print(collection.name) + print(collection.source) + + # You can also iterate specifically over the collection + # names with the .names() helper. + collection_name="my_collection" + for collection_name in client.list_collections().names(): + print(collection_name) + ``` + """ + pass + + @abstractmethod + def delete_collection(self, name: str): + """Deletes a collection. + + :param: name: The name of the collection + + Deleting a collection is an irreversible operation. All data + in the collection will be lost. + + This method tells Pinecone you would like to delete a collection, + but it takes a few moments to complete the operation. Use the + `describe_collection()` method to confirm that the collection + has been deleted. + """ + pass + + @abstractmethod + def describe_collection(self, name: str): + """Describes a collection. + :param: The name of the collection + :return: Description of the collection + + ```python + from pinecone import Pinecone + + client = Pinecone() + + description = client.describe_collection("my_collection") + print(description.name) + print(description.source) + print(description.status) + print(description.size) + ``` + """ + pass + + @abstractmethod + def Index(self, name: str = "", host: str = "", **kwargs): + """ + Target an index for data operations. + + ### Target an index by host url + + In production situations, you want to uspert or query your data as quickly + as possible. If you know in advance the host url of your index, you can + eliminate a round trip to the Pinecone control plane by specifying the + host of the index. + + ```python + import os + from pinecone import Pinecone + + api_key = os.environ.get("PINECONE_API_KEY") + index_host = os.environ.get("PINECONE_INDEX_HOST") + + pc = Pinecone(api_key=api_key) + index = pc.Index(host=index_host) + + # Now you're ready to perform data operations + index.query(vector=[...], top_k=10) + ``` + + To find your host url, you can use the Pinecone control plane to describe + the index. The host url is returned in the response. Or, alternatively, the + host is displayed in the Pinecone web console. + + ```python + import os + from pinecone import Pinecone + + pc = Pinecone( + api_key=os.environ.get("PINECONE_API_KEY") + ) + + host = pc.describe_index('index-name').host + ``` + + ### Target an index by name (not recommended for production) + + For more casual usage, such as when you are playing and exploring with Pinecone + in a notebook setting, you can also target an index by name. If you use this + approach, the client may need to perform an extra call to the Pinecone control + plane to get the host url on your behalf to get the index host. + + The client will cache the index host for future use whenever it is seen, so you + will only incur the overhead of only one call. But this approach is not + recommended for production usage. + + ```python + import os + from pinecone import Pinecone, ServerlessSpec + + api_key = os.environ.get("PINECONE_API_KEY") + + pc = Pinecone(api_key=api_key) + pc.create_index( + name='my_index', + dimension=1536, + metric='cosine', + spec=ServerlessSpec(cloud='aws', region='us-west-2') + ) + index = pc.Index('my_index') + + # Now you're ready to perform data operations + index.query(vector=[...], top_k=10) + ``` + + Arguments: + name: The name of the index to target. If you specify the name of the index, the client will + fetch the host url from the Pinecone control plane. + host: The host url of the index to target. If you specify the host url, the client will use + the host url directly without making any additional calls to the control plane. + pool_threads: The number of threads to use when making parallel requests by calling index methods with optional kwarg async_req=True, or using methods that make use of parallelism automatically such as query_namespaces(). Default: 1 + connection_pool_maxsize: The maximum number of connections to keep in the connection pool. Default: 5 * multiprocessing.cpu_count() + """ + pass From 63cfef3b7b6f9895ecbea89b835e6a8e8378f931 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 13 Dec 2024 14:30:16 -0500 Subject: [PATCH 03/21] Introduce Vector and SparseValue dataclasses, adjust object factories and tests --- pinecone/control/pinecone.py | 73 +- pinecone/control/pinecone_interface.py | 14 +- .../core/grpc/protos/db_data_2025_01_pb2.py | 130 +++ .../core/grpc/protos/db_data_2025_01_pb2.pyi | 259 +++++ .../grpc/protos/db_data_2025_01_pb2_grpc.py | 309 +++++ .../core/grpc/protos/vector_service_pb2.py | 286 ----- .../core/grpc/protos/vector_service_pb2.pyi | 1034 ----------------- .../grpc/protos/vector_service_pb2_grpc.py | 394 ------- .../db_control/api/manage_indexes_api.py | 4 +- .../openapi/db_data/model/upsert_record.py | 22 +- .../db_data/model/upsert_record_embed.py | 254 ---- .../core/openapi/db_data/models/__init__.py | 1 - pinecone/data/__init__.py | 1 + pinecone/data/dataclasses/__init__.py | 2 + pinecone/data/dataclasses/sparse_values.py | 19 + pinecone/data/dataclasses/utils.py | 11 + pinecone/data/dataclasses/vector.py | 34 + pinecone/data/index.py | 3 +- ...or_factory.py => sparse_values_factory.py} | 13 +- pinecone/data/vector_factory.py | 47 +- pinecone/grpc/__init__.py | 6 +- pinecone/grpc/index_grpc.py | 41 +- pinecone/grpc/sparse_values_factory.py | 52 +- pinecone/grpc/vector_factory_grpc.py | 31 +- pinecone/utils/constants.py | 4 +- pinecone/utils/docslinks.py | 5 + .../control/pod/test_collections.py | 1 - .../control/serverless/conftest.py | 15 - .../test_create_index_sl_happy_path.py | 13 +- .../control/serverless/test_sparse_index.py | 73 ++ tests/integration/data/test_upsert.py | 87 -- tests/integration/data/test_upsert_dense.py | 47 + tests/integration/data/test_upsert_hybrid.py | 52 + tests/integration/data/test_upsert_sparse.py | 91 ++ tests/integration/helpers/helpers.py | 11 +- tests/unit/data/test_datetime_parsing.py | 3 +- tests/unit/data/test_vector_factory.py | 113 +- .../test_grpc_index_describe_index_stats.py | 2 +- tests/unit_grpc/test_grpc_index_fetch.py | 2 +- tests/unit_grpc/test_grpc_index_query.py | 2 +- tests/unit_grpc/test_grpc_index_update.py | 2 +- tests/unit_grpc/test_grpc_index_upsert.py | 25 +- tests/unit_grpc/test_sparse_values_factory.py | 18 +- tests/unit_grpc/test_vector_factory_grpc.py | 424 +++++-- 44 files changed, 1704 insertions(+), 2326 deletions(-) create mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2.py create mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2.pyi create mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py delete mode 100644 pinecone/core/grpc/protos/vector_service_pb2.py delete mode 100644 pinecone/core/grpc/protos/vector_service_pb2.pyi delete mode 100644 pinecone/core/grpc/protos/vector_service_pb2_grpc.py delete mode 100644 pinecone/core/openapi/db_data/model/upsert_record_embed.py create mode 100644 pinecone/data/dataclasses/__init__.py create mode 100644 pinecone/data/dataclasses/sparse_values.py create mode 100644 pinecone/data/dataclasses/utils.py create mode 100644 pinecone/data/dataclasses/vector.py rename pinecone/data/{sparse_vector_factory.py => sparse_values_factory.py} (73%) create mode 100644 tests/integration/control/serverless/test_sparse_index.py delete mode 100644 tests/integration/data/test_upsert.py create mode 100644 tests/integration/data/test_upsert_dense.py create mode 100644 tests/integration/data/test_upsert_hybrid.py create mode 100644 tests/integration/data/test_upsert_sparse.py diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 4d6d27a46..a8dd81ce0 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -1,6 +1,6 @@ import time import logging -from typing import Optional, Dict, Any, Union, List, Tuple, Literal +from typing import Optional, Dict, Any, Union, Literal from .index_host_store import IndexHostStore from .pinecone_interface import PineconeDBControlInterface @@ -27,6 +27,7 @@ from pinecone.core.openapi.db_control import API_VERSION from pinecone.models import ServerlessSpec, PodSpec, IndexModel, IndexList, CollectionList from .langchain_import_warnings import _build_langchain_attribute_error_message +from pinecone.utils import parse_non_empty_args, docslinks from pinecone.data import _Index @@ -115,30 +116,12 @@ def load_plugins(self): except Exception as e: logger.error(f"Error loading plugins: {e}") - def create_index( - self, - name: str, - dimension: int, - spec: Union[Dict, ServerlessSpec, PodSpec], - metric: Optional[str] = "cosine", - timeout: Optional[int] = None, - deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", - ): - api_instance = self.index_api - - 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'") - + def _parse_index_spec(self, spec: Union[Dict, ServerlessSpec, PodSpec]) -> IndexSpec: if isinstance(spec, dict): if "serverless" in spec: index_spec = IndexSpec(serverless=ServerlessSpecModel(**spec["serverless"])) elif "pod" in spec: - args_dict = _parse_non_empty_args( + args_dict = parse_non_empty_args( [ ("environment", spec["pod"].get("environment")), ("metadata_config", spec["pod"].get("metadata_config")), @@ -160,7 +143,7 @@ def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: serverless=ServerlessSpecModel(cloud=spec.cloud, region=spec.region) ) elif isinstance(spec, PodSpec): - args_dict = _parse_non_empty_args( + args_dict = parse_non_empty_args( [ ("replicas", spec.replicas), ("shards", spec.shards), @@ -179,13 +162,42 @@ def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: else: raise TypeError("spec must be of type dict, ServerlessSpec, or PodSpec") + return index_spec + + def create_index( + self, + name: str, + spec: Union[Dict, ServerlessSpec, PodSpec], + dimension: Optional[int] = None, + metric: Optional[Literal["cosine", "euclidean", "dotproduct"]] = "cosine", + timeout: Optional[int] = None, + deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", + vector_type: Optional[Literal["dense", "sparse"]] = "dense", + ): + api_instance = self.index_api + + if vector_type == "sparse" and dimension is not None: + raise ValueError("dimension should not be specified for sparse indexes") + + if deletion_protection in ["enabled", "disabled"]: + dp = DeletionProtection(deletion_protection) + else: + raise ValueError("deletion_protection must be either 'enabled' or 'disabled'") + + index_spec = self._parse_index_spec(spec) + api_instance.create_index( create_index_request=CreateIndexRequest( - name=name, - dimension=dimension, - metric=metric, - spec=index_spec, - deletion_protection=dp, + **parse_non_empty_args( + [ + ("name", name), + ("dimension", dimension), + ("metric", metric), + ("spec", index_spec), + ("deletion_protection", dp), + ("vector_type", vector_type), + ] + ) ) ) @@ -194,20 +206,25 @@ def is_ready(): ready = status["ready"] return ready + total_wait_time = 0 if timeout == -1: + logger.debug(f"Skipping wait for index {name} to be ready") return if timeout is None: while not is_ready(): + total_wait_time += 5 time.sleep(5) else: while (not is_ready()) and timeout >= 0: + total_wait_time += 5 time.sleep(5) timeout -= 5 if timeout and timeout < 0: + logger.error(f"Index {name} is not ready. Timeout reached.") raise ( TimeoutError( "Please call the describe_index API ({}) to confirm index status.".format( - "https://www.pinecone.io/docs/api/operation/describe_index/" + docslinks["API_DESCRIBE_INDEX"] ) ) ) diff --git a/pinecone/control/pinecone_interface.py b/pinecone/control/pinecone_interface.py index 2780d6b23..1a6381bdd 100644 --- a/pinecone/control/pinecone_interface.py +++ b/pinecone/control/pinecone_interface.py @@ -175,11 +175,12 @@ def __init__( def create_index( self, name: str, - dimension: int, spec: Union[Dict, ServerlessSpec, PodSpec], + dimension: Optional[int], metric: Optional[str] = "cosine", timeout: Optional[int] = None, deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", + vector_type: Optional[str] = "dense", ): """Creates a Pinecone index. @@ -187,20 +188,23 @@ def create_index( cannot be changed once created. Allowed characters are lowercase letters, numbers, and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. :type name: str - :param dimension: The dimension of vectors that will be inserted in the index. This should - match the dimension of the embeddings you will be inserting. For example, if you are using - OpenAI's CLIP model, you should use `dimension=1536`. - :type dimension: int :param metric: Type of metric used in the vector index when querying, one of `{"cosine", "dotproduct", "euclidean"}`. Defaults to `"cosine"`. Defaults to `"cosine"`. :type metric: str, optional :param spec: A dictionary containing configurations describing how the index should be deployed. For serverless indexes, specify region and cloud. For pod indexes, specify replicas, shards, pods, pod_type, metadata_config, and source_collection. :type spec: Dict + :param dimension: The dimension of vectors that will be inserted in the index. This should + match the dimension of the embeddings you will be inserting. For example, if you are using + OpenAI's CLIP model, you should use `dimension=1536`. Dimension is a required field when + creating an index with vector_type="dense". + :type dimension: int :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" + :param vector_type: The type of vectors to be stored in the index. One of `{"dense", "sparse"}`. Default: "dense" + :type vector_type: str, optional ### Creating a serverless index diff --git a/pinecone/core/grpc/protos/db_data_2025_01_pb2.py b/pinecone/core/grpc/protos/db_data_2025_01_pb2.py new file mode 100644 index 000000000..ab0491f8c --- /dev/null +++ b/pinecone/core/grpc/protos/db_data_2025_01_pb2.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: db_data_2025-01.proto +# Protobuf Python Version: 5.29.0 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 5, + 29, + 0, + '', + 'db_data_2025-01.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x64\x62_data_2025-01.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\"J\n\x0cSparseValues\x12\x1d\n\x07indices\x18\x01 \x03(\rB\x03\xe0\x41\x02R\x07indices\x12\x1b\n\x06values\x18\x02 \x03(\x02\x42\x03\xe0\x41\x02R\x06values\"\x9e\x01\n\x06Vector\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x16\n\x06values\x18\x02 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x04 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x33\n\x08metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x08metadata\"\xba\x01\n\x0cScoredVector\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x14\n\x05score\x18\x02 \x01(\x02R\x05score\x12\x16\n\x06values\x18\x03 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x33\n\x08metadata\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x08metadata\"\xa1\x01\n\x0cRequestUnion\x12(\n\x06upsert\x18\x01 \x01(\x0b\x32\x0e.UpsertRequestH\x00R\x06upsert\x12(\n\x06\x64\x65lete\x18\x02 \x01(\x0b\x32\x0e.DeleteRequestH\x00R\x06\x64\x65lete\x12(\n\x06update\x18\x03 \x01(\x0b\x32\x0e.UpdateRequestH\x00R\x06updateB\x13\n\x11RequestUnionInner\"U\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x03\xe0\x41\x02R\x07vectors\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"7\n\x0eUpsertResponse\x12%\n\x0eupserted_count\x18\x01 \x01(\rR\rupsertedCount\"\x8f\x01\n\rDeleteRequest\x12\x10\n\x03ids\x18\x01 \x03(\tR\x03ids\x12\x1d\n\ndelete_all\x18\x02 \x01(\x08R\tdeleteAll\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12/\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"\x10\n\x0e\x44\x65leteResponse\"C\n\x0c\x46\x65tchRequest\x12\x15\n\x03ids\x18\x01 \x03(\tB\x03\xe0\x41\x02R\x03ids\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"\xd6\x01\n\rFetchResponse\x12\x35\n\x07vectors\x18\x01 \x03(\x0b\x32\x1b.FetchResponse.VectorsEntryR\x07vectors\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x03 \x01(\x0b\x32\x06.UsageH\x00R\x05usage\x88\x01\x01\x1a\x43\n\x0cVectorsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x1d\n\x05value\x18\x02 \x01(\x0b\x32\x07.VectorR\x05value:\x02\x38\x01\x42\x08\n\x06_usage\"\xbd\x01\n\x0bListRequest\x12\x1b\n\x06prefix\x18\x01 \x01(\tH\x00R\x06prefix\x88\x01\x01\x12\x19\n\x05limit\x18\x02 \x01(\rH\x01R\x05limit\x88\x01\x01\x12.\n\x10pagination_token\x18\x03 \x01(\tH\x02R\x0fpaginationToken\x88\x01\x01\x12\x1c\n\tnamespace\x18\x04 \x01(\tR\tnamespaceB\t\n\x07_prefixB\x08\n\x06_limitB\x13\n\x11_pagination_token\" \n\nPagination\x12\x12\n\x04next\x18\x01 \x01(\tR\x04next\"\x1a\n\x08ListItem\x12\x0e\n\x02id\x18\x01 \x01(\tR\x02id\"\xbf\x01\n\x0cListResponse\x12#\n\x07vectors\x18\x01 \x03(\x0b\x32\t.ListItemR\x07vectors\x12\x30\n\npagination\x18\x02 \x01(\x0b\x32\x0b.PaginationH\x00R\npagination\x88\x01\x01\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageH\x01R\x05usage\x88\x01\x01\x42\r\n\x0b_paginationB\x08\n\x06_usage\"\xbd\x01\n\x0bQueryVector\x12\x16\n\x06values\x18\x01 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x13\n\x05top_k\x18\x02 \x01(\rR\x04topK\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12/\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"\xd1\x02\n\x0cQueryRequest\x12\x1c\n\tnamespace\x18\x01 \x01(\tR\tnamespace\x12\x18\n\x05top_k\x18\x02 \x01(\rB\x03\xe0\x41\x02R\x04topK\x12/\n\x06\x66ilter\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\x12%\n\x0einclude_values\x18\x04 \x01(\x08R\rincludeValues\x12)\n\x10include_metadata\x18\x05 \x01(\x08R\x0fincludeMetadata\x12*\n\x07queries\x18\x06 \x03(\x0b\x32\x0c.QueryVectorB\x02\x18\x01R\x07queries\x12\x16\n\x06vector\x18\x07 \x03(\x02R\x06vector\x12\x32\n\rsparse_vector\x18\t \x01(\x0b\x32\r.SparseValuesR\x0csparseVector\x12\x0e\n\x02id\x18\x08 \x01(\tR\x02id\"[\n\x12SingleQueryResults\x12\'\n\x07matches\x18\x01 \x03(\x0b\x32\r.ScoredVectorR\x07matches\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"\xb6\x01\n\rQueryResponse\x12\x31\n\x07results\x18\x01 \x03(\x0b\x32\x13.SingleQueryResultsB\x02\x18\x01R\x07results\x12\'\n\x07matches\x18\x02 \x03(\x0b\x32\r.ScoredVectorR\x07matches\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageH\x00R\x05usage\x88\x01\x01\x42\x08\n\x06_usage\":\n\x05Usage\x12\"\n\nread_units\x18\x01 \x01(\rH\x00R\treadUnits\x88\x01\x01\x42\r\n\x0b_read_units\"\xca\x01\n\rUpdateRequest\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x16\n\x06values\x18\x02 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12:\n\x0cset_metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x0bsetMetadata\x12\x1c\n\tnamespace\x18\x04 \x01(\tR\tnamespace\"\x10\n\x0eUpdateResponse\"L\n\x19\x44\x65scribeIndexStatsRequest\x12/\n\x06\x66ilter\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"5\n\x10NamespaceSummary\x12!\n\x0cvector_count\x18\x01 \x01(\rR\x0bvectorCount\"\x9f\x03\n\x1a\x44\x65scribeIndexStatsResponse\x12K\n\nnamespaces\x18\x01 \x03(\x0b\x32+.DescribeIndexStatsResponse.NamespacesEntryR\nnamespaces\x12!\n\tdimension\x18\x02 \x01(\rH\x00R\tdimension\x88\x01\x01\x12%\n\x0eindex_fullness\x18\x03 \x01(\x02R\rindexFullness\x12,\n\x12total_vector_count\x18\x04 \x01(\rR\x10totalVectorCount\x12\x1b\n\x06metric\x18\x05 \x01(\tH\x01R\x06metric\x88\x01\x01\x12$\n\x0bvector_type\x18\x06 \x01(\tH\x02R\nvectorType\x88\x01\x01\x1aP\n\x0fNamespacesEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x11.NamespaceSummaryR\x05value:\x02\x38\x01\x42\x0c\n\n_dimensionB\t\n\x07_metricB\x0e\n\x0c_vector_type2\xb9\x04\n\rVectorService\x12\x45\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse\"\x1a\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/upsert:\x01*\x12X\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"-\x82\xd3\xe4\x93\x02\'\"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x12>\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse\"\x16\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x12:\n\x04List\x12\x0c.ListRequest\x1a\r.ListResponse\"\x15\x82\xd3\xe4\x93\x02\x0f\x12\r/vectors/list\x12\x39\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse\"\x11\x82\xd3\xe4\x93\x02\x0b\"\x06/query:\x01*\x12\x45\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse\"\x1a\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/update:\x01*\x12\x88\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse\"9\x82\xd3\xe4\x93\x02\x33\"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_statsBS\n\x11io.pinecone.protoP\x01Z None: ... + +class Vector(_message.Message): + __slots__ = ("id", "values", "sparse_values", "metadata") + ID_FIELD_NUMBER: _ClassVar[int] + VALUES_FIELD_NUMBER: _ClassVar[int] + SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + id: str + values: _containers.RepeatedScalarFieldContainer[float] + sparse_values: SparseValues + metadata: _struct_pb2.Struct + def __init__(self, id: _Optional[str] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... + +class ScoredVector(_message.Message): + __slots__ = ("id", "score", "values", "sparse_values", "metadata") + ID_FIELD_NUMBER: _ClassVar[int] + SCORE_FIELD_NUMBER: _ClassVar[int] + VALUES_FIELD_NUMBER: _ClassVar[int] + SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + id: str + score: float + values: _containers.RepeatedScalarFieldContainer[float] + sparse_values: SparseValues + metadata: _struct_pb2.Struct + def __init__(self, id: _Optional[str] = ..., score: _Optional[float] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... + +class RequestUnion(_message.Message): + __slots__ = ("upsert", "delete", "update") + UPSERT_FIELD_NUMBER: _ClassVar[int] + DELETE_FIELD_NUMBER: _ClassVar[int] + UPDATE_FIELD_NUMBER: _ClassVar[int] + upsert: UpsertRequest + delete: DeleteRequest + update: UpdateRequest + def __init__(self, upsert: _Optional[_Union[UpsertRequest, _Mapping]] = ..., delete: _Optional[_Union[DeleteRequest, _Mapping]] = ..., update: _Optional[_Union[UpdateRequest, _Mapping]] = ...) -> None: ... + +class UpsertRequest(_message.Message): + __slots__ = ("vectors", "namespace") + VECTORS_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + vectors: _containers.RepeatedCompositeFieldContainer[Vector] + namespace: str + def __init__(self, vectors: _Optional[_Iterable[_Union[Vector, _Mapping]]] = ..., namespace: _Optional[str] = ...) -> None: ... + +class UpsertResponse(_message.Message): + __slots__ = ("upserted_count",) + UPSERTED_COUNT_FIELD_NUMBER: _ClassVar[int] + upserted_count: int + def __init__(self, upserted_count: _Optional[int] = ...) -> None: ... + +class DeleteRequest(_message.Message): + __slots__ = ("ids", "delete_all", "namespace", "filter") + IDS_FIELD_NUMBER: _ClassVar[int] + DELETE_ALL_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + ids: _containers.RepeatedScalarFieldContainer[str] + delete_all: bool + namespace: str + filter: _struct_pb2.Struct + def __init__(self, ids: _Optional[_Iterable[str]] = ..., delete_all: bool = ..., namespace: _Optional[str] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... + +class DeleteResponse(_message.Message): + __slots__ = () + def __init__(self) -> None: ... + +class FetchRequest(_message.Message): + __slots__ = ("ids", "namespace") + IDS_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + ids: _containers.RepeatedScalarFieldContainer[str] + namespace: str + def __init__(self, ids: _Optional[_Iterable[str]] = ..., namespace: _Optional[str] = ...) -> None: ... + +class FetchResponse(_message.Message): + __slots__ = ("vectors", "namespace", "usage") + class VectorsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: Vector + def __init__(self, key: _Optional[str] = ..., value: _Optional[_Union[Vector, _Mapping]] = ...) -> None: ... + VECTORS_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + USAGE_FIELD_NUMBER: _ClassVar[int] + vectors: _containers.MessageMap[str, Vector] + namespace: str + usage: Usage + def __init__(self, vectors: _Optional[_Mapping[str, Vector]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... + +class ListRequest(_message.Message): + __slots__ = ("prefix", "limit", "pagination_token", "namespace") + PREFIX_FIELD_NUMBER: _ClassVar[int] + LIMIT_FIELD_NUMBER: _ClassVar[int] + PAGINATION_TOKEN_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + prefix: str + limit: int + pagination_token: str + namespace: str + def __init__(self, prefix: _Optional[str] = ..., limit: _Optional[int] = ..., pagination_token: _Optional[str] = ..., namespace: _Optional[str] = ...) -> None: ... + +class Pagination(_message.Message): + __slots__ = ("next",) + NEXT_FIELD_NUMBER: _ClassVar[int] + next: str + def __init__(self, next: _Optional[str] = ...) -> None: ... + +class ListItem(_message.Message): + __slots__ = ("id",) + ID_FIELD_NUMBER: _ClassVar[int] + id: str + def __init__(self, id: _Optional[str] = ...) -> None: ... + +class ListResponse(_message.Message): + __slots__ = ("vectors", "pagination", "namespace", "usage") + VECTORS_FIELD_NUMBER: _ClassVar[int] + PAGINATION_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + USAGE_FIELD_NUMBER: _ClassVar[int] + vectors: _containers.RepeatedCompositeFieldContainer[ListItem] + pagination: Pagination + namespace: str + usage: Usage + def __init__(self, vectors: _Optional[_Iterable[_Union[ListItem, _Mapping]]] = ..., pagination: _Optional[_Union[Pagination, _Mapping]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... + +class QueryVector(_message.Message): + __slots__ = ("values", "sparse_values", "top_k", "namespace", "filter") + VALUES_FIELD_NUMBER: _ClassVar[int] + SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] + TOP_K_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + values: _containers.RepeatedScalarFieldContainer[float] + sparse_values: SparseValues + top_k: int + namespace: str + filter: _struct_pb2.Struct + def __init__(self, values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., top_k: _Optional[int] = ..., namespace: _Optional[str] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... + +class QueryRequest(_message.Message): + __slots__ = ("namespace", "top_k", "filter", "include_values", "include_metadata", "queries", "vector", "sparse_vector", "id") + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + TOP_K_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + INCLUDE_VALUES_FIELD_NUMBER: _ClassVar[int] + INCLUDE_METADATA_FIELD_NUMBER: _ClassVar[int] + QUERIES_FIELD_NUMBER: _ClassVar[int] + VECTOR_FIELD_NUMBER: _ClassVar[int] + SPARSE_VECTOR_FIELD_NUMBER: _ClassVar[int] + ID_FIELD_NUMBER: _ClassVar[int] + namespace: str + top_k: int + filter: _struct_pb2.Struct + include_values: bool + include_metadata: bool + queries: _containers.RepeatedCompositeFieldContainer[QueryVector] + vector: _containers.RepeatedScalarFieldContainer[float] + sparse_vector: SparseValues + id: str + def __init__(self, namespace: _Optional[str] = ..., top_k: _Optional[int] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., include_values: bool = ..., include_metadata: bool = ..., queries: _Optional[_Iterable[_Union[QueryVector, _Mapping]]] = ..., vector: _Optional[_Iterable[float]] = ..., sparse_vector: _Optional[_Union[SparseValues, _Mapping]] = ..., id: _Optional[str] = ...) -> None: ... + +class SingleQueryResults(_message.Message): + __slots__ = ("matches", "namespace") + MATCHES_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + matches: _containers.RepeatedCompositeFieldContainer[ScoredVector] + namespace: str + def __init__(self, matches: _Optional[_Iterable[_Union[ScoredVector, _Mapping]]] = ..., namespace: _Optional[str] = ...) -> None: ... + +class QueryResponse(_message.Message): + __slots__ = ("results", "matches", "namespace", "usage") + RESULTS_FIELD_NUMBER: _ClassVar[int] + MATCHES_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + USAGE_FIELD_NUMBER: _ClassVar[int] + results: _containers.RepeatedCompositeFieldContainer[SingleQueryResults] + matches: _containers.RepeatedCompositeFieldContainer[ScoredVector] + namespace: str + usage: Usage + def __init__(self, results: _Optional[_Iterable[_Union[SingleQueryResults, _Mapping]]] = ..., matches: _Optional[_Iterable[_Union[ScoredVector, _Mapping]]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... + +class Usage(_message.Message): + __slots__ = ("read_units",) + READ_UNITS_FIELD_NUMBER: _ClassVar[int] + read_units: int + def __init__(self, read_units: _Optional[int] = ...) -> None: ... + +class UpdateRequest(_message.Message): + __slots__ = ("id", "values", "sparse_values", "set_metadata", "namespace") + ID_FIELD_NUMBER: _ClassVar[int] + VALUES_FIELD_NUMBER: _ClassVar[int] + SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] + SET_METADATA_FIELD_NUMBER: _ClassVar[int] + NAMESPACE_FIELD_NUMBER: _ClassVar[int] + id: str + values: _containers.RepeatedScalarFieldContainer[float] + sparse_values: SparseValues + set_metadata: _struct_pb2.Struct + namespace: str + def __init__(self, id: _Optional[str] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., set_metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., namespace: _Optional[str] = ...) -> None: ... + +class UpdateResponse(_message.Message): + __slots__ = () + def __init__(self) -> None: ... + +class DescribeIndexStatsRequest(_message.Message): + __slots__ = ("filter",) + FILTER_FIELD_NUMBER: _ClassVar[int] + filter: _struct_pb2.Struct + def __init__(self, filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... + +class NamespaceSummary(_message.Message): + __slots__ = ("vector_count",) + VECTOR_COUNT_FIELD_NUMBER: _ClassVar[int] + vector_count: int + def __init__(self, vector_count: _Optional[int] = ...) -> None: ... + +class DescribeIndexStatsResponse(_message.Message): + __slots__ = ("namespaces", "dimension", "index_fullness", "total_vector_count", "metric", "vector_type") + class NamespacesEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: NamespaceSummary + def __init__(self, key: _Optional[str] = ..., value: _Optional[_Union[NamespaceSummary, _Mapping]] = ...) -> None: ... + NAMESPACES_FIELD_NUMBER: _ClassVar[int] + DIMENSION_FIELD_NUMBER: _ClassVar[int] + INDEX_FULLNESS_FIELD_NUMBER: _ClassVar[int] + TOTAL_VECTOR_COUNT_FIELD_NUMBER: _ClassVar[int] + METRIC_FIELD_NUMBER: _ClassVar[int] + VECTOR_TYPE_FIELD_NUMBER: _ClassVar[int] + namespaces: _containers.MessageMap[str, NamespaceSummary] + dimension: int + index_fullness: float + total_vector_count: int + metric: str + vector_type: str + def __init__(self, namespaces: _Optional[_Mapping[str, NamespaceSummary]] = ..., dimension: _Optional[int] = ..., index_fullness: _Optional[float] = ..., total_vector_count: _Optional[int] = ..., metric: _Optional[str] = ..., vector_type: _Optional[str] = ...) -> None: ... diff --git a/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py b/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py new file mode 100644 index 000000000..dbdd5fb00 --- /dev/null +++ b/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py @@ -0,0 +1,309 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import pinecone.core.grpc.protos.db_data_2025_01_pb2 as db__data__2025__01__pb2 + + +class VectorServiceStub(object): + """The `VectorService` interface is exposed by Pinecone's vector index services. + This service could also be called a `gRPC` service or a `REST`-like api. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Upsert = channel.unary_unary( + '/VectorService/Upsert', + request_serializer=db__data__2025__01__pb2.UpsertRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.UpsertResponse.FromString, + ) + self.Delete = channel.unary_unary( + '/VectorService/Delete', + request_serializer=db__data__2025__01__pb2.DeleteRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.DeleteResponse.FromString, + ) + self.Fetch = channel.unary_unary( + '/VectorService/Fetch', + request_serializer=db__data__2025__01__pb2.FetchRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.FetchResponse.FromString, + ) + self.List = channel.unary_unary( + '/VectorService/List', + request_serializer=db__data__2025__01__pb2.ListRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.ListResponse.FromString, + ) + self.Query = channel.unary_unary( + '/VectorService/Query', + request_serializer=db__data__2025__01__pb2.QueryRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.QueryResponse.FromString, + ) + self.Update = channel.unary_unary( + '/VectorService/Update', + request_serializer=db__data__2025__01__pb2.UpdateRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.UpdateResponse.FromString, + ) + self.DescribeIndexStats = channel.unary_unary( + '/VectorService/DescribeIndexStats', + request_serializer=db__data__2025__01__pb2.DescribeIndexStatsRequest.SerializeToString, + response_deserializer=db__data__2025__01__pb2.DescribeIndexStatsResponse.FromString, + ) + + +class VectorServiceServicer(object): + """The `VectorService` interface is exposed by Pinecone's vector index services. + This service could also be called a `gRPC` service or a `REST`-like api. + """ + + def Upsert(self, request, context): + """Upsert vectors + + The `upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. + + For guidance and examples, see [Upsert data](https://docs.pinecone.io/guides/data/upsert-data). + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Delete(self, request, context): + """Delete vectors + + The `delete` operation deletes vectors, by id, from a single namespace. + + For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Fetch(self, request, context): + """Fetch vectors + + The `fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. + + For guidance and examples, see [Fetch data](https://docs.pinecone.io/guides/data/fetch-data). + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def List(self, request, context): + """List vector IDs + + The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. + + `list` returns up to 100 IDs at a time by default in sorted order (bitwise/"C" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. + + For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). + + **Note:** `list` is supported only for serverless indexes. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Query(self, request, context): + """Query vectors + + The `query` operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. + + For guidance and examples, see [Query data](https://docs.pinecone.io/guides/data/query-data). + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Update(self, request, context): + """Update a vector + + The `update` operation updates a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. + + For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DescribeIndexStats(self, request, context): + """Get index stats + + The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. + + Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_VectorServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Upsert': grpc.unary_unary_rpc_method_handler( + servicer.Upsert, + request_deserializer=db__data__2025__01__pb2.UpsertRequest.FromString, + response_serializer=db__data__2025__01__pb2.UpsertResponse.SerializeToString, + ), + 'Delete': grpc.unary_unary_rpc_method_handler( + servicer.Delete, + request_deserializer=db__data__2025__01__pb2.DeleteRequest.FromString, + response_serializer=db__data__2025__01__pb2.DeleteResponse.SerializeToString, + ), + 'Fetch': grpc.unary_unary_rpc_method_handler( + servicer.Fetch, + request_deserializer=db__data__2025__01__pb2.FetchRequest.FromString, + response_serializer=db__data__2025__01__pb2.FetchResponse.SerializeToString, + ), + 'List': grpc.unary_unary_rpc_method_handler( + servicer.List, + request_deserializer=db__data__2025__01__pb2.ListRequest.FromString, + response_serializer=db__data__2025__01__pb2.ListResponse.SerializeToString, + ), + 'Query': grpc.unary_unary_rpc_method_handler( + servicer.Query, + request_deserializer=db__data__2025__01__pb2.QueryRequest.FromString, + response_serializer=db__data__2025__01__pb2.QueryResponse.SerializeToString, + ), + 'Update': grpc.unary_unary_rpc_method_handler( + servicer.Update, + request_deserializer=db__data__2025__01__pb2.UpdateRequest.FromString, + response_serializer=db__data__2025__01__pb2.UpdateResponse.SerializeToString, + ), + 'DescribeIndexStats': grpc.unary_unary_rpc_method_handler( + servicer.DescribeIndexStats, + request_deserializer=db__data__2025__01__pb2.DescribeIndexStatsRequest.FromString, + response_serializer=db__data__2025__01__pb2.DescribeIndexStatsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'VectorService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class VectorService(object): + """The `VectorService` interface is exposed by Pinecone's vector index services. + This service could also be called a `gRPC` service or a `REST`-like api. + """ + + @staticmethod + def Upsert(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/Upsert', + db__data__2025__01__pb2.UpsertRequest.SerializeToString, + db__data__2025__01__pb2.UpsertResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Delete(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/Delete', + db__data__2025__01__pb2.DeleteRequest.SerializeToString, + db__data__2025__01__pb2.DeleteResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Fetch(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/Fetch', + db__data__2025__01__pb2.FetchRequest.SerializeToString, + db__data__2025__01__pb2.FetchResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def List(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/List', + db__data__2025__01__pb2.ListRequest.SerializeToString, + db__data__2025__01__pb2.ListResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Query(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/Query', + db__data__2025__01__pb2.QueryRequest.SerializeToString, + db__data__2025__01__pb2.QueryResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Update(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/Update', + db__data__2025__01__pb2.UpdateRequest.SerializeToString, + db__data__2025__01__pb2.UpdateResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def DescribeIndexStats(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/VectorService/DescribeIndexStats', + db__data__2025__01__pb2.DescribeIndexStatsRequest.SerializeToString, + db__data__2025__01__pb2.DescribeIndexStatsResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/pinecone/core/grpc/protos/vector_service_pb2.py b/pinecone/core/grpc/protos/vector_service_pb2.py deleted file mode 100644 index f9ffc212a..000000000 --- a/pinecone/core/grpc/protos/vector_service_pb2.py +++ /dev/null @@ -1,286 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: vector_service.proto -# Protobuf Python Version: 4.25.1 -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import descriptor_pool as _descriptor_pool -from google.protobuf import symbol_database as _symbol_database -from google.protobuf.internal import builder as _builder - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import ( - field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2, -) -from protoc_gen_openapiv2.options import ( - annotations_pb2 as protoc__gen__openapiv2_dot_options_dot_annotations__pb2, -) - - -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n\x14vector_service.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a.protoc-gen-openapiv2/options/annotations.proto"\x80\x01\n\x0cSparseValues\x12\x36\n\x07indices\x18\x01 \x03(\rB%\x92\x41\x1eJ\x16[1, 312, 822, 14, 980]x\xe8\x07\x80\x01\x01\xe2\x41\x01\x02\x12\x38\n\x06values\x18\x02 \x03(\x02\x42(\x92\x41!J\x19[0.1, 0.2, 0.3, 0.4, 0.5]x\xe8\x07\x80\x01\x01\xe2\x41\x01\x02"\xff\x01\n\x06Vector\x12-\n\x02id\x18\x01 \x01(\tB!\x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe2\x41\x01\x02\x12H\n\x06values\x18\x02 \x03(\x02\x42\x38\x92\x41\x31J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\xa0\x9c\x01\x80\x01\x01\xe2\x41\x01\x02\x12$\n\rsparse_values\x18\x04 \x01(\x0b\x32\r.SparseValues\x12V\n\x08metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructB+\x92\x41(J&{"genre": "documentary", "year": 2019}"\x94\x02\n\x0cScoredVector\x12-\n\x02id\x18\x01 \x01(\tB!\x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe2\x41\x01\x02\x12\x18\n\x05score\x18\x02 \x01(\x02\x42\t\x92\x41\x06J\x04\x30.08\x12=\n\x06values\x18\x03 \x03(\x02\x42-\x92\x41*J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]\x12$\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValues\x12V\n\x08metadata\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructB+\x92\x41(J&{"genre": "documentary", "year": 2019}"\x89\x01\n\x0cRequestUnion\x12 \n\x06upsert\x18\x01 \x01(\x0b\x32\x0e.UpsertRequestH\x00\x12 \n\x06\x64\x65lete\x18\x02 \x01(\x0b\x32\x0e.DeleteRequestH\x00\x12 \n\x06update\x18\x03 \x01(\x0b\x32\x0e.UpdateRequestH\x00\x42\x13\n\x11RequestUnionInner"e\n\rUpsertRequest\x12\'\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\r\x92\x41\x06x\xe8\x07\x80\x01\x01\xe2\x41\x01\x02\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace""1\n\x0eUpsertResponse\x12\x1f\n\x0eupserted_count\x18\x01 \x01(\rB\x07\x92\x41\x04J\x02\x31\x30"\xb6\x01\n\rDeleteRequest\x12(\n\x03ids\x18\x01 \x03(\tB\x1b\x92\x41\x18J\x10["id-0", "id-1"]x\xe8\x07\x80\x01\x01\x12%\n\ndelete_all\x18\x02 \x01(\x08\x42\x11\x92\x41\x0e:\x05\x66\x61lseJ\x05\x66\x61lse\x12+\n\tnamespace\x18\x03 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"\x12\'\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct"\x10\n\x0e\x44\x65leteResponse"i\n\x0c\x46\x65tchRequest\x12,\n\x03ids\x18\x01 \x03(\tB\x1f\x92\x41\x18J\x10["id-0", "id-1"]x\xe8\x07\x80\x01\x01\xe2\x41\x01\x02\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace""\xe1\x01\n\rFetchResponse\x12,\n\x07vectors\x18\x01 \x03(\x0b\x32\x1b.FetchResponse.VectorsEntry\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"\x12\x32\n\x05usage\x18\x03 \x01(\x0b\x32\x06.UsageB\x16\x92\x41\x13J\x11{"read_units": 5}H\x00\x88\x01\x01\x1a\x37\n\x0cVectorsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x16\n\x05value\x18\x02 \x01(\x0b\x32\x07.Vector:\x02\x38\x01\x42\x08\n\x06_usage"\xf8\x01\n\x0bListRequest\x12,\n\x06prefix\x18\x01 \x01(\tB\x17\x92\x41\x14J\x0c"document1#"x\xe8\x07\x80\x01\x01H\x00\x88\x01\x01\x12 \n\x05limit\x18\x02 \x01(\rB\x0c\x92\x41\t:\x03\x31\x30\x30J\x02\x31\x32H\x01\x88\x01\x01\x12\x42\n\x10pagination_token\x18\x03 \x01(\tB#\x92\x41 J\x1e"Tm90aGluZyB0byBzZWUgaGVyZQo="H\x02\x88\x01\x01\x12+\n\tnamespace\x18\x04 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"B\t\n\x07_prefixB\x08\n\x06_limitB\x13\n\x11_pagination_token"?\n\nPagination\x12\x31\n\x04next\x18\x01 \x01(\tB#\x92\x41 J\x1e"Tm90aGluZyB0byBzZWUgaGVyZQo="",\n\x08ListItem\x12 \n\x02id\x18\x01 \x01(\tB\x14\x92\x41\x11J\x0f"document1#abb""\x83\x02\n\x0cListResponse\x12S\n\x07vectors\x18\x01 \x03(\x0b\x32\t.ListItemB7\x92\x41\x34J2[{"id": "document1#abb"}, {"id": "document1#abc"}]\x12$\n\npagination\x18\x02 \x01(\x0b\x32\x0b.PaginationH\x00\x88\x01\x01\x12+\n\tnamespace\x18\x03 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"\x12\x32\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageB\x16\x92\x41\x13J\x11{"read_units": 1}H\x01\x88\x01\x01\x42\r\n\x0b_paginationB\x08\n\x06_usage"\xd1\x02\n\x0bQueryVector\x12H\n\x06values\x18\x01 \x03(\x02\x42\x38\x92\x41\x31J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\xa0\x9c\x01\x80\x01\x01\xe2\x41\x01\x02\x12$\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValues\x12(\n\x05top_k\x18\x02 \x01(\rB\x19\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\x12+\n\tnamespace\x18\x03 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"\x12{\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructBR\x92\x41OJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}"\xfb\x03\n\x0cQueryRequest\x12+\n\tnamespace\x18\x01 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace"\x12,\n\x05top_k\x18\x02 \x01(\rB\x1d\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\xe2\x41\x01\x02\x12{\n\x06\x66ilter\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructBR\x92\x41OJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}\x12(\n\x0einclude_values\x18\x04 \x01(\x08\x42\x10\x92\x41\r:\x05\x66\x61lseJ\x04true\x12*\n\x10include_metadata\x18\x05 \x01(\x08\x42\x10\x92\x41\r:\x05\x66\x61lseJ\x04true\x12)\n\x07queries\x18\x06 \x03(\x0b\x32\x0c.QueryVectorB\n\x18\x01\x92\x41\x05x\n\x80\x01\x01\x12\x44\n\x06vector\x18\x07 \x03(\x02\x42\x34\x92\x41\x31J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\xa0\x9c\x01\x80\x01\x01\x12$\n\rsparse_vector\x18\t \x01(\x0b\x32\r.SparseValues\x12&\n\x02id\x18\x08 \x01(\tB\x1a\x92\x41\x17J\x12"example-vector-1"x\x80\x04"a\n\x12SingleQueryResults\x12\x1e\n\x07matches\x18\x01 \x03(\x0b\x32\r.ScoredVector\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace""\xaa\x01\n\rQueryResponse\x12(\n\x07results\x18\x01 \x03(\x0b\x32\x13.SingleQueryResultsB\x02\x18\x01\x12\x1e\n\x07matches\x18\x02 \x03(\x0b\x32\r.ScoredVector\x12\x11\n\tnamespace\x18\x03 \x01(\t\x12\x32\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageB\x16\x92\x41\x13J\x11{"read_units": 5}H\x00\x88\x01\x01\x42\x08\n\x06_usage"7\n\x05Usage\x12\x1f\n\nread_units\x18\x01 \x01(\rB\x06\x92\x41\x03J\x01\x35H\x00\x88\x01\x01\x42\r\n\x0b_read_units"\xb3\x02\n\rUpdateRequest\x12-\n\x02id\x18\x01 \x01(\tB!\x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe2\x41\x01\x02\x12\x44\n\x06values\x18\x02 \x03(\x02\x42\x34\x92\x41\x31J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\xa0\x9c\x01\x80\x01\x01\x12$\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValues\x12Z\n\x0cset_metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructB+\x92\x41(J&{"genre": "documentary", "year": 2019}\x12+\n\tnamespace\x18\x04 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace""\x10\n\x0eUpdateResponse"D\n\x19\x44\x65scribeIndexStatsRequest\x12\'\n\x06\x66ilter\x18\x01 \x01(\x0b\x32\x17.google.protobuf.Struct"4\n\x10NamespaceSummary\x12 \n\x0cvector_count\x18\x01 \x01(\rB\n\x92\x41\x07J\x05\x35\x30\x30\x30\x30"\x9a\x03\n\x1a\x44\x65scribeIndexStatsResponse\x12?\n\nnamespaces\x18\x01 \x03(\x0b\x32+.DescribeIndexStatsResponse.NamespacesEntry\x12\x1c\n\tdimension\x18\x02 \x01(\rB\t\x92\x41\x06J\x04\x31\x30\x32\x34\x12 \n\x0eindex_fullness\x18\x03 \x01(\x02\x42\x08\x92\x41\x05J\x03\x30.4\x12&\n\x12total_vector_count\x18\x04 \x01(\rB\n\x92\x41\x07J\x05\x38\x30\x30\x30\x30\x1a\x44\n\x0fNamespacesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12 \n\x05value\x18\x02 \x01(\x0b\x32\x11.NamespaceSummary:\x02\x38\x01:\x8c\x01\x92\x41\x88\x01\x32\x85\x01{"namespaces": {"": {"vectorCount": 50000}, "example-namespace-2": {"vectorCount": 30000}}, "dimension": 1024, "index_fullness": 0.4}2\x95\x06\n\rVectorService\x12\x63\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse"8\x92\x41\x1b\n\x11Vector Operations*\x06upsert\x82\xd3\xe4\x93\x02\x14"\x0f/vectors/upsert:\x01*\x12v\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse"K\x92\x41\x1b\n\x11Vector Operations*\x06\x64\x65lete\x82\xd3\xe4\x93\x02\'"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x12[\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse"3\x92\x41\x1a\n\x11Vector Operations*\x05\x66\x65tch\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x12V\n\x04List\x12\x0c.ListRequest\x1a\r.ListResponse"1\x92\x41\x19\n\x11Vector Operations*\x04list\x82\xd3\xe4\x93\x02\x0f\x12\r/vectors/list\x12V\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse".\x92\x41\x1a\n\x11Vector Operations*\x05query\x82\xd3\xe4\x93\x02\x0b"\x06/query:\x01*\x12\x63\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse"8\x92\x41\x1b\n\x11Vector Operations*\x06update\x82\xd3\xe4\x93\x02\x14"\x0f/vectors/update:\x01*\x12\xb4\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse"e\x92\x41)\n\x11Vector Operations*\x14\x64\x65scribe_index_stats\x82\xd3\xe4\x93\x02\x33"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_statsB\x8f\x03\n\x11io.pinecone.protoP\x01Z+github.com/pinecone-io/go-pinecone/pinecone\x92\x41\xc9\x02\x12K\n\x0cPinecone API";\n\x0fPinecone.io Ops\x12\x13https://pinecone.io\x1a\x13support@pinecone.io\x1a\x0c{index_host}*\x01\x02\x32\x10\x61pplication/json:\x10\x61pplication/jsonZx\nv\n\nApiKeyAuth\x12h\x08\x02\x12YAn API Key is required to call Pinecone APIs. Get yours at https://www.pinecone.io/start/\x1a\x07\x41pi-Key \x02\x62\x10\n\x0e\n\nApiKeyAuth\x12\x00r9\n\x19More Pinecone.io API docs\x12\x1chttps://www.pinecone.io/docsb\x06proto3' -) - -_globals = globals() -_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) -_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "vector_service_pb2", _globals) -if _descriptor._USE_C_DESCRIPTORS == False: - _globals["DESCRIPTOR"]._options = None - _globals["DESCRIPTOR"]._serialized_options = ( - b'\n\021io.pinecone.protoP\001Z+github.com/pinecone-io/go-pinecone/pinecone\222A\311\002\022K\n\014Pinecone API";\n\017Pinecone.io Ops\022\023https://pinecone.io\032\023support@pinecone.io\032\014{index_host}*\001\0022\020application/json:\020application/jsonZx\nv\n\nApiKeyAuth\022h\010\002\022YAn API Key is required to call Pinecone APIs. Get yours at https://www.pinecone.io/start/\032\007Api-Key \002b\020\n\016\n\nApiKeyAuth\022\000r9\n\031More Pinecone.io API docs\022\034https://www.pinecone.io/docs' - ) - _globals["_SPARSEVALUES"].fields_by_name["indices"]._options = None - _globals["_SPARSEVALUES"].fields_by_name[ - "indices" - ]._serialized_options = b"\222A\036J\026[1, 312, 822, 14, 980]x\350\007\200\001\001\342A\001\002" - _globals["_SPARSEVALUES"].fields_by_name["values"]._options = None - _globals["_SPARSEVALUES"].fields_by_name[ - "values" - ]._serialized_options = b"\222A!J\031[0.1, 0.2, 0.3, 0.4, 0.5]x\350\007\200\001\001\342A\001\002" - _globals["_VECTOR"].fields_by_name["id"]._options = None - _globals["_VECTOR"].fields_by_name[ - "id" - ]._serialized_options = b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\342A\001\002' - _globals["_VECTOR"].fields_by_name["values"]._options = None - _globals["_VECTOR"].fields_by_name[ - "values" - ]._serialized_options = b"\222A1J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\240\234\001\200\001\001\342A\001\002" - _globals["_VECTOR"].fields_by_name["metadata"]._options = None - _globals["_VECTOR"].fields_by_name[ - "metadata" - ]._serialized_options = b'\222A(J&{"genre": "documentary", "year": 2019}' - _globals["_SCOREDVECTOR"].fields_by_name["id"]._options = None - _globals["_SCOREDVECTOR"].fields_by_name[ - "id" - ]._serialized_options = b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\342A\001\002' - _globals["_SCOREDVECTOR"].fields_by_name["score"]._options = None - _globals["_SCOREDVECTOR"].fields_by_name["score"]._serialized_options = b"\222A\006J\0040.08" - _globals["_SCOREDVECTOR"].fields_by_name["values"]._options = None - _globals["_SCOREDVECTOR"].fields_by_name[ - "values" - ]._serialized_options = b"\222A*J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]" - _globals["_SCOREDVECTOR"].fields_by_name["metadata"]._options = None - _globals["_SCOREDVECTOR"].fields_by_name[ - "metadata" - ]._serialized_options = b'\222A(J&{"genre": "documentary", "year": 2019}' - _globals["_UPSERTREQUEST"].fields_by_name["vectors"]._options = None - _globals["_UPSERTREQUEST"].fields_by_name[ - "vectors" - ]._serialized_options = b"\222A\006x\350\007\200\001\001\342A\001\002" - _globals["_UPSERTREQUEST"].fields_by_name["namespace"]._options = None - _globals["_UPSERTREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_UPSERTRESPONSE"].fields_by_name["upserted_count"]._options = None - _globals["_UPSERTRESPONSE"].fields_by_name["upserted_count"]._serialized_options = b"\222A\004J\00210" - _globals["_DELETEREQUEST"].fields_by_name["ids"]._options = None - _globals["_DELETEREQUEST"].fields_by_name[ - "ids" - ]._serialized_options = b'\222A\030J\020["id-0", "id-1"]x\350\007\200\001\001' - _globals["_DELETEREQUEST"].fields_by_name["delete_all"]._options = None - _globals["_DELETEREQUEST"].fields_by_name["delete_all"]._serialized_options = b"\222A\016:\005falseJ\005false" - _globals["_DELETEREQUEST"].fields_by_name["namespace"]._options = None - _globals["_DELETEREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_FETCHREQUEST"].fields_by_name["ids"]._options = None - _globals["_FETCHREQUEST"].fields_by_name[ - "ids" - ]._serialized_options = b'\222A\030J\020["id-0", "id-1"]x\350\007\200\001\001\342A\001\002' - _globals["_FETCHREQUEST"].fields_by_name["namespace"]._options = None - _globals["_FETCHREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_FETCHRESPONSE_VECTORSENTRY"]._options = None - _globals["_FETCHRESPONSE_VECTORSENTRY"]._serialized_options = b"8\001" - _globals["_FETCHRESPONSE"].fields_by_name["namespace"]._options = None - _globals["_FETCHRESPONSE"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_FETCHRESPONSE"].fields_by_name["usage"]._options = None - _globals["_FETCHRESPONSE"].fields_by_name["usage"]._serialized_options = b'\222A\023J\021{"read_units": 5}' - _globals["_LISTREQUEST"].fields_by_name["prefix"]._options = None - _globals["_LISTREQUEST"].fields_by_name[ - "prefix" - ]._serialized_options = b'\222A\024J\014"document1#"x\350\007\200\001\001' - _globals["_LISTREQUEST"].fields_by_name["limit"]._options = None - _globals["_LISTREQUEST"].fields_by_name["limit"]._serialized_options = b"\222A\t:\003100J\00212" - _globals["_LISTREQUEST"].fields_by_name["pagination_token"]._options = None - _globals["_LISTREQUEST"].fields_by_name[ - "pagination_token" - ]._serialized_options = b'\222A J\036"Tm90aGluZyB0byBzZWUgaGVyZQo="' - _globals["_LISTREQUEST"].fields_by_name["namespace"]._options = None - _globals["_LISTREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_PAGINATION"].fields_by_name["next"]._options = None - _globals["_PAGINATION"].fields_by_name["next"]._serialized_options = b'\222A J\036"Tm90aGluZyB0byBzZWUgaGVyZQo="' - _globals["_LISTITEM"].fields_by_name["id"]._options = None - _globals["_LISTITEM"].fields_by_name["id"]._serialized_options = b'\222A\021J\017"document1#abb"' - _globals["_LISTRESPONSE"].fields_by_name["vectors"]._options = None - _globals["_LISTRESPONSE"].fields_by_name[ - "vectors" - ]._serialized_options = b'\222A4J2[{"id": "document1#abb"}, {"id": "document1#abc"}]' - _globals["_LISTRESPONSE"].fields_by_name["namespace"]._options = None - _globals["_LISTRESPONSE"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_LISTRESPONSE"].fields_by_name["usage"]._options = None - _globals["_LISTRESPONSE"].fields_by_name["usage"]._serialized_options = b'\222A\023J\021{"read_units": 1}' - _globals["_QUERYVECTOR"].fields_by_name["values"]._options = None - _globals["_QUERYVECTOR"].fields_by_name[ - "values" - ]._serialized_options = b"\222A1J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\240\234\001\200\001\001\342A\001\002" - _globals["_QUERYVECTOR"].fields_by_name["top_k"]._options = None - _globals["_QUERYVECTOR"].fields_by_name[ - "top_k" - ]._serialized_options = b"\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?" - _globals["_QUERYVECTOR"].fields_by_name["namespace"]._options = None - _globals["_QUERYVECTOR"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_QUERYVECTOR"].fields_by_name["filter"]._options = None - _globals["_QUERYVECTOR"].fields_by_name[ - "filter" - ]._serialized_options = b'\222AOJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}' - _globals["_QUERYREQUEST"].fields_by_name["namespace"]._options = None - _globals["_QUERYREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_QUERYREQUEST"].fields_by_name["top_k"]._options = None - _globals["_QUERYREQUEST"].fields_by_name[ - "top_k" - ]._serialized_options = b"\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?\342A\001\002" - _globals["_QUERYREQUEST"].fields_by_name["filter"]._options = None - _globals["_QUERYREQUEST"].fields_by_name[ - "filter" - ]._serialized_options = b'\222AOJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}' - _globals["_QUERYREQUEST"].fields_by_name["include_values"]._options = None - _globals["_QUERYREQUEST"].fields_by_name["include_values"]._serialized_options = b"\222A\r:\005falseJ\004true" - _globals["_QUERYREQUEST"].fields_by_name["include_metadata"]._options = None - _globals["_QUERYREQUEST"].fields_by_name["include_metadata"]._serialized_options = b"\222A\r:\005falseJ\004true" - _globals["_QUERYREQUEST"].fields_by_name["queries"]._options = None - _globals["_QUERYREQUEST"].fields_by_name["queries"]._serialized_options = b"\030\001\222A\005x\n\200\001\001" - _globals["_QUERYREQUEST"].fields_by_name["vector"]._options = None - _globals["_QUERYREQUEST"].fields_by_name[ - "vector" - ]._serialized_options = b"\222A1J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\240\234\001\200\001\001" - _globals["_QUERYREQUEST"].fields_by_name["id"]._options = None - _globals["_QUERYREQUEST"].fields_by_name["id"]._serialized_options = b'\222A\027J\022"example-vector-1"x\200\004' - _globals["_SINGLEQUERYRESULTS"].fields_by_name["namespace"]._options = None - _globals["_SINGLEQUERYRESULTS"].fields_by_name[ - "namespace" - ]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_QUERYRESPONSE"].fields_by_name["results"]._options = None - _globals["_QUERYRESPONSE"].fields_by_name["results"]._serialized_options = b"\030\001" - _globals["_QUERYRESPONSE"].fields_by_name["usage"]._options = None - _globals["_QUERYRESPONSE"].fields_by_name["usage"]._serialized_options = b'\222A\023J\021{"read_units": 5}' - _globals["_USAGE"].fields_by_name["read_units"]._options = None - _globals["_USAGE"].fields_by_name["read_units"]._serialized_options = b"\222A\003J\0015" - _globals["_UPDATEREQUEST"].fields_by_name["id"]._options = None - _globals["_UPDATEREQUEST"].fields_by_name[ - "id" - ]._serialized_options = b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\342A\001\002' - _globals["_UPDATEREQUEST"].fields_by_name["values"]._options = None - _globals["_UPDATEREQUEST"].fields_by_name[ - "values" - ]._serialized_options = b"\222A1J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]x\240\234\001\200\001\001" - _globals["_UPDATEREQUEST"].fields_by_name["set_metadata"]._options = None - _globals["_UPDATEREQUEST"].fields_by_name[ - "set_metadata" - ]._serialized_options = b'\222A(J&{"genre": "documentary", "year": 2019}' - _globals["_UPDATEREQUEST"].fields_by_name["namespace"]._options = None - _globals["_UPDATEREQUEST"].fields_by_name["namespace"]._serialized_options = b'\222A\025J\023"example-namespace"' - _globals["_NAMESPACESUMMARY"].fields_by_name["vector_count"]._options = None - _globals["_NAMESPACESUMMARY"].fields_by_name["vector_count"]._serialized_options = b"\222A\007J\00550000" - _globals["_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY"]._options = None - _globals["_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY"]._serialized_options = b"8\001" - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name["dimension"]._options = None - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name["dimension"]._serialized_options = b"\222A\006J\0041024" - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name["index_fullness"]._options = None - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name["index_fullness"]._serialized_options = b"\222A\005J\0030.4" - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name["total_vector_count"]._options = None - _globals["_DESCRIBEINDEXSTATSRESPONSE"].fields_by_name[ - "total_vector_count" - ]._serialized_options = b"\222A\007J\00580000" - _globals["_DESCRIBEINDEXSTATSRESPONSE"]._options = None - _globals["_DESCRIBEINDEXSTATSRESPONSE"]._serialized_options = ( - b'\222A\210\0012\205\001{"namespaces": {"": {"vectorCount": 50000}, "example-namespace-2": {"vectorCount": 30000}}, "dimension": 1024, "index_fullness": 0.4}' - ) - _globals["_VECTORSERVICE"].methods_by_name["Upsert"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "Upsert" - ]._serialized_options = ( - b'\222A\033\n\021Vector Operations*\006upsert\202\323\344\223\002\024"\017/vectors/upsert:\001*' - ) - _globals["_VECTORSERVICE"].methods_by_name["Delete"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "Delete" - ]._serialized_options = b"\222A\033\n\021Vector Operations*\006delete\202\323\344\223\002'\"\017/vectors/delete:\001*Z\021*\017/vectors/delete" - _globals["_VECTORSERVICE"].methods_by_name["Fetch"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "Fetch" - ]._serialized_options = b"\222A\032\n\021Vector Operations*\005fetch\202\323\344\223\002\020\022\016/vectors/fetch" - _globals["_VECTORSERVICE"].methods_by_name["List"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "List" - ]._serialized_options = b"\222A\031\n\021Vector Operations*\004list\202\323\344\223\002\017\022\r/vectors/list" - _globals["_VECTORSERVICE"].methods_by_name["Query"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "Query" - ]._serialized_options = b'\222A\032\n\021Vector Operations*\005query\202\323\344\223\002\013"\006/query:\001*' - _globals["_VECTORSERVICE"].methods_by_name["Update"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "Update" - ]._serialized_options = ( - b'\222A\033\n\021Vector Operations*\006update\202\323\344\223\002\024"\017/vectors/update:\001*' - ) - _globals["_VECTORSERVICE"].methods_by_name["DescribeIndexStats"]._options = None - _globals["_VECTORSERVICE"].methods_by_name[ - "DescribeIndexStats" - ]._serialized_options = b'\222A)\n\021Vector Operations*\024describe_index_stats\202\323\344\223\0023"\025/describe_index_stats:\001*Z\027\022\025/describe_index_stats' - _globals["_SPARSEVALUES"]._serialized_start = 166 - _globals["_SPARSEVALUES"]._serialized_end = 294 - _globals["_VECTOR"]._serialized_start = 297 - _globals["_VECTOR"]._serialized_end = 552 - _globals["_SCOREDVECTOR"]._serialized_start = 555 - _globals["_SCOREDVECTOR"]._serialized_end = 831 - _globals["_REQUESTUNION"]._serialized_start = 834 - _globals["_REQUESTUNION"]._serialized_end = 971 - _globals["_UPSERTREQUEST"]._serialized_start = 973 - _globals["_UPSERTREQUEST"]._serialized_end = 1074 - _globals["_UPSERTRESPONSE"]._serialized_start = 1076 - _globals["_UPSERTRESPONSE"]._serialized_end = 1125 - _globals["_DELETEREQUEST"]._serialized_start = 1128 - _globals["_DELETEREQUEST"]._serialized_end = 1310 - _globals["_DELETERESPONSE"]._serialized_start = 1312 - _globals["_DELETERESPONSE"]._serialized_end = 1328 - _globals["_FETCHREQUEST"]._serialized_start = 1330 - _globals["_FETCHREQUEST"]._serialized_end = 1435 - _globals["_FETCHRESPONSE"]._serialized_start = 1438 - _globals["_FETCHRESPONSE"]._serialized_end = 1663 - _globals["_FETCHRESPONSE_VECTORSENTRY"]._serialized_start = 1598 - _globals["_FETCHRESPONSE_VECTORSENTRY"]._serialized_end = 1653 - _globals["_LISTREQUEST"]._serialized_start = 1666 - _globals["_LISTREQUEST"]._serialized_end = 1914 - _globals["_PAGINATION"]._serialized_start = 1916 - _globals["_PAGINATION"]._serialized_end = 1979 - _globals["_LISTITEM"]._serialized_start = 1981 - _globals["_LISTITEM"]._serialized_end = 2025 - _globals["_LISTRESPONSE"]._serialized_start = 2028 - _globals["_LISTRESPONSE"]._serialized_end = 2287 - _globals["_QUERYVECTOR"]._serialized_start = 2290 - _globals["_QUERYVECTOR"]._serialized_end = 2627 - _globals["_QUERYREQUEST"]._serialized_start = 2630 - _globals["_QUERYREQUEST"]._serialized_end = 3137 - _globals["_SINGLEQUERYRESULTS"]._serialized_start = 3139 - _globals["_SINGLEQUERYRESULTS"]._serialized_end = 3236 - _globals["_QUERYRESPONSE"]._serialized_start = 3239 - _globals["_QUERYRESPONSE"]._serialized_end = 3409 - _globals["_USAGE"]._serialized_start = 3411 - _globals["_USAGE"]._serialized_end = 3466 - _globals["_UPDATEREQUEST"]._serialized_start = 3469 - _globals["_UPDATEREQUEST"]._serialized_end = 3776 - _globals["_UPDATERESPONSE"]._serialized_start = 3778 - _globals["_UPDATERESPONSE"]._serialized_end = 3794 - _globals["_DESCRIBEINDEXSTATSREQUEST"]._serialized_start = 3796 - _globals["_DESCRIBEINDEXSTATSREQUEST"]._serialized_end = 3864 - _globals["_NAMESPACESUMMARY"]._serialized_start = 3866 - _globals["_NAMESPACESUMMARY"]._serialized_end = 3918 - _globals["_DESCRIBEINDEXSTATSRESPONSE"]._serialized_start = 3921 - _globals["_DESCRIBEINDEXSTATSRESPONSE"]._serialized_end = 4331 - _globals["_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY"]._serialized_start = 4120 - _globals["_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY"]._serialized_end = 4188 - _globals["_VECTORSERVICE"]._serialized_start = 4334 - _globals["_VECTORSERVICE"]._serialized_end = 5123 -# @@protoc_insertion_point(module_scope) diff --git a/pinecone/core/grpc/protos/vector_service_pb2.pyi b/pinecone/core/grpc/protos/vector_service_pb2.pyi deleted file mode 100644 index 827c301c0..000000000 --- a/pinecone/core/grpc/protos/vector_service_pb2.pyi +++ /dev/null @@ -1,1034 +0,0 @@ -""" -@generated by mypy-protobuf. Do not edit manually! -isort:skip_file -Generated file - DO NOT EDIT -This file is generated from the pinecone-io/apis repo. -Any changes made directly here WILL be overwritten. -""" - -import builtins -import collections.abc -import google.protobuf.descriptor -import google.protobuf.internal.containers -import google.protobuf.message -import google.protobuf.struct_pb2 -import typing - -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor - -@typing.final -class SparseValues(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - INDICES_FIELD_NUMBER: builtins.int - VALUES_FIELD_NUMBER: builtins.int - @property - def indices( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... - @property - def values( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... - def __init__( - self, - *, - indices: collections.abc.Iterable[builtins.int] | None = ..., - values: collections.abc.Iterable[builtins.float] | None = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal["indices", b"indices", "values", b"values"], - ) -> None: ... - -global___SparseValues = SparseValues - -@typing.final -class Vector(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - ID_FIELD_NUMBER: builtins.int - VALUES_FIELD_NUMBER: builtins.int - SPARSE_VALUES_FIELD_NUMBER: builtins.int - METADATA_FIELD_NUMBER: builtins.int - id: builtins.str - """This is the vector's unique id.""" - @property - def values( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: - """This is the vector data included in the request.""" - - @property - def sparse_values(self) -> global___SparseValues: ... - @property - def metadata(self) -> google.protobuf.struct_pb2.Struct: - """This is the metadata included in the request.""" - - def __init__( - self, - *, - id: builtins.str = ..., - values: collections.abc.Iterable[builtins.float] | None = ..., - sparse_values: global___SparseValues | None = ..., - metadata: google.protobuf.struct_pb2.Struct | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "id", - b"id", - "metadata", - b"metadata", - "sparse_values", - b"sparse_values", - "values", - b"values", - ], - ) -> None: ... - -global___Vector = Vector - -@typing.final -class ScoredVector(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - ID_FIELD_NUMBER: builtins.int - SCORE_FIELD_NUMBER: builtins.int - VALUES_FIELD_NUMBER: builtins.int - SPARSE_VALUES_FIELD_NUMBER: builtins.int - METADATA_FIELD_NUMBER: builtins.int - id: builtins.str - """This is the vector's unique id.""" - score: builtins.float - """This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.""" - @property - def values( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: - """This is the vector data, if it is requested.""" - - @property - def sparse_values(self) -> global___SparseValues: - """This is the sparse data, if it is requested.""" - - @property - def metadata(self) -> google.protobuf.struct_pb2.Struct: - """This is the metadata, if it is requested.""" - - def __init__( - self, - *, - id: builtins.str = ..., - score: builtins.float = ..., - values: collections.abc.Iterable[builtins.float] | None = ..., - sparse_values: global___SparseValues | None = ..., - metadata: google.protobuf.struct_pb2.Struct | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "id", - b"id", - "metadata", - b"metadata", - "score", - b"score", - "sparse_values", - b"sparse_values", - "values", - b"values", - ], - ) -> None: ... - -global___ScoredVector = ScoredVector - -@typing.final -class RequestUnion(google.protobuf.message.Message): - """This is a container to hold mutating vector requests. This is not actually used - in any public APIs. - """ - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - UPSERT_FIELD_NUMBER: builtins.int - DELETE_FIELD_NUMBER: builtins.int - UPDATE_FIELD_NUMBER: builtins.int - @property - def upsert(self) -> global___UpsertRequest: ... - @property - def delete(self) -> global___DeleteRequest: ... - @property - def update(self) -> global___UpdateRequest: ... - def __init__( - self, - *, - upsert: global___UpsertRequest | None = ..., - delete: global___DeleteRequest | None = ..., - update: global___UpdateRequest | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal[ - "RequestUnionInner", - b"RequestUnionInner", - "delete", - b"delete", - "update", - b"update", - "upsert", - b"upsert", - ], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "RequestUnionInner", - b"RequestUnionInner", - "delete", - b"delete", - "update", - b"update", - "upsert", - b"upsert", - ], - ) -> None: ... - def WhichOneof( - self, - oneof_group: typing.Literal["RequestUnionInner", b"RequestUnionInner"], - ) -> typing.Literal["upsert", "delete", "update"] | None: ... - -global___RequestUnion = RequestUnion - -@typing.final -class UpsertRequest(google.protobuf.message.Message): - """The request for the `upsert` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - VECTORS_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - namespace: builtins.str - """This is the namespace name where you upsert vectors.""" - @property - def vectors( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Vector]: - """An array containing the vectors to upsert. Recommended batch limit is 100 vectors.""" - - def __init__( - self, - *, - vectors: collections.abc.Iterable[global___Vector] | None = ..., - namespace: builtins.str = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal["namespace", b"namespace", "vectors", b"vectors"], - ) -> None: ... - -global___UpsertRequest = UpsertRequest - -@typing.final -class UpsertResponse(google.protobuf.message.Message): - """The response for the `upsert` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - UPSERTED_COUNT_FIELD_NUMBER: builtins.int - upserted_count: builtins.int - """The number of vectors upserted.""" - def __init__( - self, - *, - upserted_count: builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing.Literal["upserted_count", b"upserted_count"]) -> None: ... - -global___UpsertResponse = UpsertResponse - -@typing.final -class DeleteRequest(google.protobuf.message.Message): - """The request for the `Delete` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - IDS_FIELD_NUMBER: builtins.int - DELETE_ALL_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - FILTER_FIELD_NUMBER: builtins.int - delete_all: builtins.bool - """This indicates that all vectors in the index namespace should be deleted.""" - namespace: builtins.str - """The namespace to delete vectors from, if applicable.""" - @property - def ids( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: - """Vectors to delete.""" - - @property - def filter(self) -> google.protobuf.struct_pb2.Struct: - """If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive - with specifying ids to delete in the ids param or using delete_all=True. - See https://www.pinecone.io/docs/metadata-filtering/. - """ - - def __init__( - self, - *, - ids: collections.abc.Iterable[builtins.str] | None = ..., - delete_all: builtins.bool = ..., - namespace: builtins.str = ..., - filter: google.protobuf.struct_pb2.Struct | None = ..., - ) -> None: ... - def HasField(self, field_name: typing.Literal["filter", b"filter"]) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "delete_all", - b"delete_all", - "filter", - b"filter", - "ids", - b"ids", - "namespace", - b"namespace", - ], - ) -> None: ... - -global___DeleteRequest = DeleteRequest - -@typing.final -class DeleteResponse(google.protobuf.message.Message): - """The response for the `Delete` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - def __init__( - self, - ) -> None: ... - -global___DeleteResponse = DeleteResponse - -@typing.final -class FetchRequest(google.protobuf.message.Message): - """The request for the `fetch` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - IDS_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - namespace: builtins.str - @property - def ids( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: - """The vector IDs to fetch. Does not accept values containing spaces.""" - - def __init__( - self, - *, - ids: collections.abc.Iterable[builtins.str] | None = ..., - namespace: builtins.str = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal["ids", b"ids", "namespace", b"namespace"], - ) -> None: ... - -global___FetchRequest = FetchRequest - -@typing.final -class FetchResponse(google.protobuf.message.Message): - """The response for the `fetch` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - @typing.final - class VectorsEntry(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - KEY_FIELD_NUMBER: builtins.int - VALUE_FIELD_NUMBER: builtins.int - key: builtins.str - @property - def value(self) -> global___Vector: ... - def __init__( - self, - *, - key: builtins.str = ..., - value: global___Vector | None = ..., - ) -> None: ... - def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... - - VECTORS_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - USAGE_FIELD_NUMBER: builtins.int - namespace: builtins.str - """The namespace of the vectors.""" - @property - def vectors( - self, - ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Vector]: - """The fetched vectors, in the form of a map between the fetched ids and the fetched vectors""" - - @property - def usage(self) -> global___Usage: - """The usage for this operation.""" - - def __init__( - self, - *, - vectors: collections.abc.Mapping[builtins.str, global___Vector] | None = ..., - namespace: builtins.str = ..., - usage: global___Usage | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "_usage", - b"_usage", - "namespace", - b"namespace", - "usage", - b"usage", - "vectors", - b"vectors", - ], - ) -> None: ... - def WhichOneof(self, oneof_group: typing.Literal["_usage", b"_usage"]) -> typing.Literal["usage"] | None: ... - -global___FetchResponse = FetchResponse - -@typing.final -class ListRequest(google.protobuf.message.Message): - """The request for the `list` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - PREFIX_FIELD_NUMBER: builtins.int - LIMIT_FIELD_NUMBER: builtins.int - PAGINATION_TOKEN_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - prefix: builtins.str - """The vector IDs to fetch. Does not accept values containing spaces.""" - limit: builtins.int - """Max number of IDs to return per page.""" - pagination_token: builtins.str - """Pagination token to continue a previous listing operation.""" - namespace: builtins.str - def __init__( - self, - *, - prefix: builtins.str | None = ..., - limit: builtins.int | None = ..., - pagination_token: builtins.str | None = ..., - namespace: builtins.str = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal[ - "_limit", - b"_limit", - "_pagination_token", - b"_pagination_token", - "_prefix", - b"_prefix", - "limit", - b"limit", - "pagination_token", - b"pagination_token", - "prefix", - b"prefix", - ], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "_limit", - b"_limit", - "_pagination_token", - b"_pagination_token", - "_prefix", - b"_prefix", - "limit", - b"limit", - "namespace", - b"namespace", - "pagination_token", - b"pagination_token", - "prefix", - b"prefix", - ], - ) -> None: ... - @typing.overload - def WhichOneof(self, oneof_group: typing.Literal["_limit", b"_limit"]) -> typing.Literal["limit"] | None: ... - @typing.overload - def WhichOneof( - self, - oneof_group: typing.Literal["_pagination_token", b"_pagination_token"], - ) -> typing.Literal["pagination_token"] | None: ... - @typing.overload - def WhichOneof(self, oneof_group: typing.Literal["_prefix", b"_prefix"]) -> typing.Literal["prefix"] | None: ... - -global___ListRequest = ListRequest - -@typing.final -class Pagination(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - NEXT_FIELD_NUMBER: builtins.int - next: builtins.str - def __init__( - self, - *, - next: builtins.str = ..., - ) -> None: ... - def ClearField(self, field_name: typing.Literal["next", b"next"]) -> None: ... - -global___Pagination = Pagination - -@typing.final -class ListItem(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - ID_FIELD_NUMBER: builtins.int - id: builtins.str - def __init__( - self, - *, - id: builtins.str = ..., - ) -> None: ... - def ClearField(self, field_name: typing.Literal["id", b"id"]) -> None: ... - -global___ListItem = ListItem - -@typing.final -class ListResponse(google.protobuf.message.Message): - """The response for the `List` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - VECTORS_FIELD_NUMBER: builtins.int - PAGINATION_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - USAGE_FIELD_NUMBER: builtins.int - namespace: builtins.str - """The namespace of the vectors.""" - @property - def vectors( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ListItem]: - """A list of ids""" - - @property - def pagination(self) -> global___Pagination: - """Pagination token to continue past this listing""" - - @property - def usage(self) -> global___Usage: - """The usage for this operation.""" - - def __init__( - self, - *, - vectors: collections.abc.Iterable[global___ListItem] | None = ..., - pagination: global___Pagination | None = ..., - namespace: builtins.str = ..., - usage: global___Usage | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal[ - "_pagination", - b"_pagination", - "_usage", - b"_usage", - "pagination", - b"pagination", - "usage", - b"usage", - ], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "_pagination", - b"_pagination", - "_usage", - b"_usage", - "namespace", - b"namespace", - "pagination", - b"pagination", - "usage", - b"usage", - "vectors", - b"vectors", - ], - ) -> None: ... - @typing.overload - def WhichOneof( - self, oneof_group: typing.Literal["_pagination", b"_pagination"] - ) -> typing.Literal["pagination"] | None: ... - @typing.overload - def WhichOneof(self, oneof_group: typing.Literal["_usage", b"_usage"]) -> typing.Literal["usage"] | None: ... - -global___ListResponse = ListResponse - -@typing.final -class QueryVector(google.protobuf.message.Message): - """A single query vector within a `QueryRequest`.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - VALUES_FIELD_NUMBER: builtins.int - SPARSE_VALUES_FIELD_NUMBER: builtins.int - TOP_K_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - FILTER_FIELD_NUMBER: builtins.int - top_k: builtins.int - """An override for the number of results to return for this query vector.""" - namespace: builtins.str - """An override the namespace to search.""" - @property - def values( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: - """The query vector values. This should be the same length as the dimension of the index being queried.""" - - @property - def sparse_values(self) -> global___SparseValues: - """The query sparse values.""" - - @property - def filter(self) -> google.protobuf.struct_pb2.Struct: - """An override for the metadata filter to apply. This replaces the request-level filter.""" - - def __init__( - self, - *, - values: collections.abc.Iterable[builtins.float] | None = ..., - sparse_values: global___SparseValues | None = ..., - top_k: builtins.int = ..., - namespace: builtins.str = ..., - filter: google.protobuf.struct_pb2.Struct | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["filter", b"filter", "sparse_values", b"sparse_values"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "filter", - b"filter", - "namespace", - b"namespace", - "sparse_values", - b"sparse_values", - "top_k", - b"top_k", - "values", - b"values", - ], - ) -> None: ... - -global___QueryVector = QueryVector - -@typing.final -class QueryRequest(google.protobuf.message.Message): - """The request for the `query` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - NAMESPACE_FIELD_NUMBER: builtins.int - TOP_K_FIELD_NUMBER: builtins.int - FILTER_FIELD_NUMBER: builtins.int - INCLUDE_VALUES_FIELD_NUMBER: builtins.int - INCLUDE_METADATA_FIELD_NUMBER: builtins.int - QUERIES_FIELD_NUMBER: builtins.int - VECTOR_FIELD_NUMBER: builtins.int - SPARSE_VECTOR_FIELD_NUMBER: builtins.int - ID_FIELD_NUMBER: builtins.int - namespace: builtins.str - """The namespace to query.""" - top_k: builtins.int - """The number of results to return for each query.""" - include_values: builtins.bool - """Indicates whether vector values are included in the response.""" - include_metadata: builtins.bool - """Indicates whether metadata is included in the response as well as the ids.""" - id: builtins.str - """The unique ID of the vector to be used as a query vector. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.""" - @property - def filter(self) -> google.protobuf.struct_pb2.Struct: - """The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.""" - - @property - def queries( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___QueryVector]: - """DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.""" - - @property - def vector( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: - """The query vector. This should be the same length as the dimension of the index being queried. Each `query()` request can contain only one of the parameters `id` or `vector`.""" - - @property - def sparse_vector(self) -> global___SparseValues: - """The query sparse values.""" - - def __init__( - self, - *, - namespace: builtins.str = ..., - top_k: builtins.int = ..., - filter: google.protobuf.struct_pb2.Struct | None = ..., - include_values: builtins.bool = ..., - include_metadata: builtins.bool = ..., - queries: collections.abc.Iterable[global___QueryVector] | None = ..., - vector: collections.abc.Iterable[builtins.float] | None = ..., - sparse_vector: global___SparseValues | None = ..., - id: builtins.str = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["filter", b"filter", "sparse_vector", b"sparse_vector"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "filter", - b"filter", - "id", - b"id", - "include_metadata", - b"include_metadata", - "include_values", - b"include_values", - "namespace", - b"namespace", - "queries", - b"queries", - "sparse_vector", - b"sparse_vector", - "top_k", - b"top_k", - "vector", - b"vector", - ], - ) -> None: ... - -global___QueryRequest = QueryRequest - -@typing.final -class SingleQueryResults(google.protobuf.message.Message): - """The query results for a single `QueryVector`""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - MATCHES_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - namespace: builtins.str - """The namespace for the vectors.""" - @property - def matches( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: - """The matches for the vectors.""" - - def __init__( - self, - *, - matches: collections.abc.Iterable[global___ScoredVector] | None = ..., - namespace: builtins.str = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal["matches", b"matches", "namespace", b"namespace"], - ) -> None: ... - -global___SingleQueryResults = SingleQueryResults - -@typing.final -class QueryResponse(google.protobuf.message.Message): - """The response for the `query` operation. These are the matches found for a particular query vector. The matches are ordered from most similar to least similar.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - RESULTS_FIELD_NUMBER: builtins.int - MATCHES_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - USAGE_FIELD_NUMBER: builtins.int - namespace: builtins.str - """The namespace for the vectors.""" - @property - def results( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SingleQueryResults]: - """DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.""" - - @property - def matches( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: - """The matches for the vectors.""" - - @property - def usage(self) -> global___Usage: - """The usage for this operation.""" - - def __init__( - self, - *, - results: collections.abc.Iterable[global___SingleQueryResults] | None = ..., - matches: collections.abc.Iterable[global___ScoredVector] | None = ..., - namespace: builtins.str = ..., - usage: global___Usage | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "_usage", - b"_usage", - "matches", - b"matches", - "namespace", - b"namespace", - "results", - b"results", - "usage", - b"usage", - ], - ) -> None: ... - def WhichOneof(self, oneof_group: typing.Literal["_usage", b"_usage"]) -> typing.Literal["usage"] | None: ... - -global___QueryResponse = QueryResponse - -@typing.final -class Usage(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - READ_UNITS_FIELD_NUMBER: builtins.int - read_units: builtins.int - """The number of read units consumed by this operation.""" - def __init__( - self, - *, - read_units: builtins.int | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"], - ) -> None: ... - def WhichOneof( - self, oneof_group: typing.Literal["_read_units", b"_read_units"] - ) -> typing.Literal["read_units"] | None: ... - -global___Usage = Usage - -@typing.final -class UpdateRequest(google.protobuf.message.Message): - """The request for the `update` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - ID_FIELD_NUMBER: builtins.int - VALUES_FIELD_NUMBER: builtins.int - SPARSE_VALUES_FIELD_NUMBER: builtins.int - SET_METADATA_FIELD_NUMBER: builtins.int - NAMESPACE_FIELD_NUMBER: builtins.int - id: builtins.str - """Vector's unique id.""" - namespace: builtins.str - """Namespace name where to update the vector.""" - @property - def values( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: - """Vector data.""" - - @property - def sparse_values(self) -> global___SparseValues: ... - @property - def set_metadata(self) -> google.protobuf.struct_pb2.Struct: - """Metadata to *set* for the vector.""" - - def __init__( - self, - *, - id: builtins.str = ..., - values: collections.abc.Iterable[builtins.float] | None = ..., - sparse_values: global___SparseValues | None = ..., - set_metadata: google.protobuf.struct_pb2.Struct | None = ..., - namespace: builtins.str = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal["set_metadata", b"set_metadata", "sparse_values", b"sparse_values"], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "id", - b"id", - "namespace", - b"namespace", - "set_metadata", - b"set_metadata", - "sparse_values", - b"sparse_values", - "values", - b"values", - ], - ) -> None: ... - -global___UpdateRequest = UpdateRequest - -@typing.final -class UpdateResponse(google.protobuf.message.Message): - """The response for the `update` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - def __init__( - self, - ) -> None: ... - -global___UpdateResponse = UpdateResponse - -@typing.final -class DescribeIndexStatsRequest(google.protobuf.message.Message): - """The request for the `describe_index_stats` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - FILTER_FIELD_NUMBER: builtins.int - @property - def filter(self) -> google.protobuf.struct_pb2.Struct: - """If this parameter is present, the operation only returns statistics - for vectors that satisfy the filter. - See https://www.pinecone.io/docs/metadata-filtering/. - """ - - def __init__( - self, - *, - filter: google.protobuf.struct_pb2.Struct | None = ..., - ) -> None: ... - def HasField(self, field_name: typing.Literal["filter", b"filter"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["filter", b"filter"]) -> None: ... - -global___DescribeIndexStatsRequest = DescribeIndexStatsRequest - -@typing.final -class NamespaceSummary(google.protobuf.message.Message): - """A summary of the contents of a namespace.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - VECTOR_COUNT_FIELD_NUMBER: builtins.int - vector_count: builtins.int - """The number of vectors stored in this namespace. Note that updates to this field may lag behind updates to the - underlying index and corresponding query results, etc. - """ - def __init__( - self, - *, - vector_count: builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing.Literal["vector_count", b"vector_count"]) -> None: ... - -global___NamespaceSummary = NamespaceSummary - -@typing.final -class DescribeIndexStatsResponse(google.protobuf.message.Message): - """The response for the `describe_index_stats` operation.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - @typing.final - class NamespacesEntry(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - KEY_FIELD_NUMBER: builtins.int - VALUE_FIELD_NUMBER: builtins.int - key: builtins.str - @property - def value(self) -> global___NamespaceSummary: ... - def __init__( - self, - *, - key: builtins.str = ..., - value: global___NamespaceSummary | None = ..., - ) -> None: ... - def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... - - NAMESPACES_FIELD_NUMBER: builtins.int - DIMENSION_FIELD_NUMBER: builtins.int - INDEX_FULLNESS_FIELD_NUMBER: builtins.int - TOTAL_VECTOR_COUNT_FIELD_NUMBER: builtins.int - dimension: builtins.int - """The dimension of the indexed vectors.""" - index_fullness: builtins.float - """The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%.""" - total_vector_count: builtins.int - """The total number of vectors in the index, regardless of whether a metadata filter expression was passed""" - @property - def namespaces( - self, - ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___NamespaceSummary]: - """A mapping for each namespace in the index from the namespace name to a - summary of its contents. If a metadata filter expression is present, the - summary will reflect only vectors matching that expression. - """ - - def __init__( - self, - *, - namespaces: collections.abc.Mapping[builtins.str, global___NamespaceSummary] | None = ..., - dimension: builtins.int = ..., - index_fullness: builtins.float = ..., - total_vector_count: builtins.int = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal[ - "dimension", - b"dimension", - "index_fullness", - b"index_fullness", - "namespaces", - b"namespaces", - "total_vector_count", - b"total_vector_count", - ], - ) -> None: ... - -global___DescribeIndexStatsResponse = DescribeIndexStatsResponse diff --git a/pinecone/core/grpc/protos/vector_service_pb2_grpc.py b/pinecone/core/grpc/protos/vector_service_pb2_grpc.py deleted file mode 100644 index 945dd7d92..000000000 --- a/pinecone/core/grpc/protos/vector_service_pb2_grpc.py +++ /dev/null @@ -1,394 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -import pinecone.core.grpc.protos.vector_service_pb2 as vector__service__pb2 - - -class VectorServiceStub(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.Upsert = channel.unary_unary( - "/VectorService/Upsert", - request_serializer=vector__service__pb2.UpsertRequest.SerializeToString, - response_deserializer=vector__service__pb2.UpsertResponse.FromString, - ) - self.Delete = channel.unary_unary( - "/VectorService/Delete", - request_serializer=vector__service__pb2.DeleteRequest.SerializeToString, - response_deserializer=vector__service__pb2.DeleteResponse.FromString, - ) - self.Fetch = channel.unary_unary( - "/VectorService/Fetch", - request_serializer=vector__service__pb2.FetchRequest.SerializeToString, - response_deserializer=vector__service__pb2.FetchResponse.FromString, - ) - self.List = channel.unary_unary( - "/VectorService/List", - request_serializer=vector__service__pb2.ListRequest.SerializeToString, - response_deserializer=vector__service__pb2.ListResponse.FromString, - ) - self.Query = channel.unary_unary( - "/VectorService/Query", - request_serializer=vector__service__pb2.QueryRequest.SerializeToString, - response_deserializer=vector__service__pb2.QueryResponse.FromString, - ) - self.Update = channel.unary_unary( - "/VectorService/Update", - request_serializer=vector__service__pb2.UpdateRequest.SerializeToString, - response_deserializer=vector__service__pb2.UpdateResponse.FromString, - ) - self.DescribeIndexStats = channel.unary_unary( - "/VectorService/DescribeIndexStats", - request_serializer=vector__service__pb2.DescribeIndexStatsRequest.SerializeToString, - response_deserializer=vector__service__pb2.DescribeIndexStatsResponse.FromString, - ) - - -class VectorServiceServicer(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - def Upsert(self, request, context): - """Upsert vectors - - The `upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. - - For guidance and examples, see [Upsert data](https://docs.pinecone.io/docs/upsert-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Delete(self, request, context): - """Delete vectors - - The `delete` operation deletes vectors, by id, from a single namespace. - - For guidance and examples, see [Delete data](https://docs.pinecone.io/docs/delete-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Fetch(self, request, context): - """Fetch vectors - - The `fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. - - For guidance and examples, see [Fetch data](https://docs.pinecone.io/docs/fetch-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def List(self, request, context): - """List vector IDs - - The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. - - `list` returns up to 100 IDs at a time by default in sorted order (bitwise/"C" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. - - For guidance and examples, see [Get record IDs](https://docs.pinecone.io/docs/get-record-ids). - - **Note:** `list` is supported only for serverless indexes. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Query(self, request, context): - """Query vectors - - The `query` operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. - - For guidance and examples, see [Query data](https://docs.pinecone.io/docs/query-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Update(self, request, context): - """Update a vector - - The `update` operation updates a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. - - For guidance and examples, see [Update data](https://docs.pinecone.io/docs/update-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DescribeIndexStats(self, request, context): - """Get index stats - - The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace and the number of dimensions, and the index fullness. - - Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. - - For pod-based indexes, the index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://www.pinecone.io/docs/api/operation/describe_index/). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_VectorServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "Upsert": grpc.unary_unary_rpc_method_handler( - servicer.Upsert, - request_deserializer=vector__service__pb2.UpsertRequest.FromString, - response_serializer=vector__service__pb2.UpsertResponse.SerializeToString, - ), - "Delete": grpc.unary_unary_rpc_method_handler( - servicer.Delete, - request_deserializer=vector__service__pb2.DeleteRequest.FromString, - response_serializer=vector__service__pb2.DeleteResponse.SerializeToString, - ), - "Fetch": grpc.unary_unary_rpc_method_handler( - servicer.Fetch, - request_deserializer=vector__service__pb2.FetchRequest.FromString, - response_serializer=vector__service__pb2.FetchResponse.SerializeToString, - ), - "List": grpc.unary_unary_rpc_method_handler( - servicer.List, - request_deserializer=vector__service__pb2.ListRequest.FromString, - response_serializer=vector__service__pb2.ListResponse.SerializeToString, - ), - "Query": grpc.unary_unary_rpc_method_handler( - servicer.Query, - request_deserializer=vector__service__pb2.QueryRequest.FromString, - response_serializer=vector__service__pb2.QueryResponse.SerializeToString, - ), - "Update": grpc.unary_unary_rpc_method_handler( - servicer.Update, - request_deserializer=vector__service__pb2.UpdateRequest.FromString, - response_serializer=vector__service__pb2.UpdateResponse.SerializeToString, - ), - "DescribeIndexStats": grpc.unary_unary_rpc_method_handler( - servicer.DescribeIndexStats, - request_deserializer=vector__service__pb2.DescribeIndexStatsRequest.FromString, - response_serializer=vector__service__pb2.DescribeIndexStatsResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler("VectorService", rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class VectorService(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - @staticmethod - def Upsert( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/Upsert", - vector__service__pb2.UpsertRequest.SerializeToString, - vector__service__pb2.UpsertResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def Delete( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/Delete", - vector__service__pb2.DeleteRequest.SerializeToString, - vector__service__pb2.DeleteResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def Fetch( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/Fetch", - vector__service__pb2.FetchRequest.SerializeToString, - vector__service__pb2.FetchResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def List( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/List", - vector__service__pb2.ListRequest.SerializeToString, - vector__service__pb2.ListResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def Query( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/Query", - vector__service__pb2.QueryRequest.SerializeToString, - vector__service__pb2.QueryResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def Update( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/Update", - vector__service__pb2.UpdateRequest.SerializeToString, - vector__service__pb2.UpdateResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DescribeIndexStats( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/VectorService/DescribeIndexStats", - vector__service__pb2.DescribeIndexStatsRequest.SerializeToString, - vector__service__pb2.DescribeIndexStatsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/pinecone/core/openapi/db_control/api/manage_indexes_api.py b/pinecone/core/openapi/db_control/api/manage_indexes_api.py index 425ef7456..f5f4b3774 100644 --- a/pinecone/core/openapi/db_control/api/manage_indexes_api.py +++ b/pinecone/core/openapi/db_control/api/manage_indexes_api.py @@ -49,7 +49,7 @@ def __init__(self, api_client=None): def __configure_index(self, index_name, configure_index_request, **kwargs): """Configure an index # noqa: E501 - This operation configures an existing index. For serverless indexes, you can configure only index deletion protection and tags. For pod-based indexes, you can configure the pod size, number of replicas, tags, 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 operation configures an existing index. For serverless indexes, you can configure index deletion protection, tags, and integrated inference embedding settings for the index. For pod-based indexes, you can configure the pod size, number of replicas, tags, 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 @@ -288,7 +288,7 @@ def __create_index(self, create_index_request, **kwargs): def __create_index_for_model(self, create_index_for_model_request, **kwargs): """Create an index for an embedding model # noqa: E501 - This operation creates a serverless index configured for a specific embedding model. # noqa: E501 + This operation creates a serverless integrated inference index for a specific embedding model. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) for available models and model details. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True diff --git a/pinecone/core/openapi/db_data/model/upsert_record.py b/pinecone/core/openapi/db_data/model/upsert_record.py index 212bfce1e..8fe914caf 100644 --- a/pinecone/core/openapi/db_data/model/upsert_record.py +++ b/pinecone/core/openapi/db_data/model/upsert_record.py @@ -29,14 +29,6 @@ from pinecone.openapi_support.exceptions import PineconeApiAttributeError -def lazy_import(): - from pinecone.core.openapi.db_data.model.upsert_record_embed import UpsertRecordEmbed - from pinecone.core.openapi.db_data.model.vector import Vector - - globals()["UpsertRecordEmbed"] = UpsertRecordEmbed - globals()["Vector"] = Vector - - class UpsertRecord(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -71,7 +63,6 @@ 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 """ - lazy_import() return (bool, dict, float, int, list, str, none_type) # noqa: E501 _nullable = False @@ -86,11 +77,8 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ - lazy_import() return { - "id": (str,), # noqa: E501 - "vector": (Vector,), # noqa: E501 - "embed": (UpsertRecordEmbed,), # noqa: E501 + "id": (str,) # noqa: E501 } @cached_property @@ -98,9 +86,7 @@ def discriminator(): return None attribute_map = { - "id": "_id", # noqa: E501 - "vector": "_vector", # noqa: E501 - "embed": "_embed", # noqa: E501 + "id": "_id" # noqa: E501 } read_only_vars = {} @@ -146,8 +132,6 @@ def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - vector (Vector): [optional] # noqa: E501 - embed (UpsertRecordEmbed): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -235,8 +219,6 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - vector (Vector): [optional] # noqa: E501 - embed (UpsertRecordEmbed): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/db_data/model/upsert_record_embed.py b/pinecone/core/openapi/db_data/model/upsert_record_embed.py deleted file mode 100644 index 53bc7bfde..000000000 --- a/pinecone/core/openapi/db_data/model/upsert_record_embed.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Pinecone Data 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: 2025-01 -Contact: support@pinecone.io -Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.openapi_support 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.openapi_support.model_utils import OpenApiModel -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -class UpsertRecordEmbed(ModelNormal): - """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. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - 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 = {} - - 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, 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 { - "inputs": ({str: (bool, dict, float, int, list, str, none_type)},) # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "inputs": "inputs" # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """UpsertRecordEmbed - a model defined in OpenAPI - - Keyword Args: - _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,) - inputs ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - 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__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - 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): # noqa: E501 - """UpsertRecordEmbed - a model defined in OpenAPI - - Keyword Args: - _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,) - inputs ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _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__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/models/__init__.py b/pinecone/core/openapi/db_data/models/__init__.py index ce76fd856..2005df6c1 100644 --- a/pinecone/core/openapi/db_data/models/__init__.py +++ b/pinecone/core/openapi/db_data/models/__init__.py @@ -49,7 +49,6 @@ from pinecone.core.openapi.db_data.model.start_import_response import StartImportResponse from pinecone.core.openapi.db_data.model.update_request import UpdateRequest from pinecone.core.openapi.db_data.model.upsert_record import UpsertRecord -from pinecone.core.openapi.db_data.model.upsert_record_embed import UpsertRecordEmbed from pinecone.core.openapi.db_data.model.upsert_request import UpsertRequest from pinecone.core.openapi.db_data.model.upsert_response import UpsertResponse from pinecone.core.openapi.db_data.model.usage import Usage diff --git a/pinecone/data/__init__.py b/pinecone/data/__init__.py index a6a791fca..a77d452af 100644 --- a/pinecone/data/__init__.py +++ b/pinecone/data/__init__.py @@ -7,6 +7,7 @@ SparseValues, Vector, ) +from .dataclasses import * from .import_error import Index, IndexClientInstantiationError from .errors import ( VectorDictionaryMissingKeysError, diff --git a/pinecone/data/dataclasses/__init__.py b/pinecone/data/dataclasses/__init__.py new file mode 100644 index 000000000..fddb08b19 --- /dev/null +++ b/pinecone/data/dataclasses/__init__.py @@ -0,0 +1,2 @@ +from .sparse_values import SparseValues +from .vector import Vector diff --git a/pinecone/data/dataclasses/sparse_values.py b/pinecone/data/dataclasses/sparse_values.py new file mode 100644 index 000000000..c5a34a29b --- /dev/null +++ b/pinecone/data/dataclasses/sparse_values.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass + +from typing import Any, Dict, List +from .utils import DictLike + + +@dataclass +class SparseValues(DictLike): + indices: List[int] + values: List[float] + + def to_dict(self) -> Dict[str, Any]: + return {"indices": self.indices, "values": self.values} + + @staticmethod + def from_dict(sparse_values_dict: Dict[str, Any]) -> "SparseValues": + return SparseValues( + indices=sparse_values_dict["indices"], values=sparse_values_dict["values"] + ) diff --git a/pinecone/data/dataclasses/utils.py b/pinecone/data/dataclasses/utils.py new file mode 100644 index 000000000..29c8e4e4f --- /dev/null +++ b/pinecone/data/dataclasses/utils.py @@ -0,0 +1,11 @@ +class DictLike: + def __getitem__(self, key): + if key in self.__dataclass_fields__: + return getattr(self, key) + raise KeyError(f"{key} is not a valid field") + + def __setitem__(self, key, value): + if key in self.__dataclass_fields__: + setattr(self, key, value) + else: + raise KeyError(f"{key} is not a valid field") diff --git a/pinecone/data/dataclasses/vector.py b/pinecone/data/dataclasses/vector.py new file mode 100644 index 000000000..56c21a835 --- /dev/null +++ b/pinecone/data/dataclasses/vector.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union +from .sparse_values import SparseValues +from .utils import DictLike + +from dataclasses import dataclass, field + + +@dataclass +class Vector(DictLike): + id: str + values: List[float] = field(default_factory=list) + metadata: Optional[Dict[str, Union[str, List[str]]]] = None + sparse_values: Optional[SparseValues] = None + + def __post_init__(self): + if self.sparse_values is None and len(self.values) == 0: + raise ValueError("The values and sparse_values fields cannot both be empty") + + def to_dict(self) -> Dict[str, Any]: + vector_dict = {"id": self.id, "values": self.values} + if self.metadata is not None: + vector_dict["metadata"] = self.metadata + if self.sparse_values is not None: + vector_dict["sparse_values"] = self.sparse_values.to_dict() + return vector_dict + + @staticmethod + def from_dict(vector_dict: Dict[str, Any]) -> "Vector": + return Vector( + id=vector_dict["id"], + values=vector_dict["values"], + metadata=vector_dict.get("metadata"), + sparse_values=SparseValues.from_dict(vector_dict.get("sparse_values")), + ) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 9f52589c4..88a0d5465 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -14,10 +14,9 @@ QueryResponse, IndexDescription as DescribeIndexStatsResponse, UpsertResponse, - Vector, ListResponse, - SparseValues, ) +from .dataclasses import Vector, SparseValues from .interfaces import IndexInterface from .request_factory import IndexRequestFactory from .features.bulk_import import ImportFeatureMixin diff --git a/pinecone/data/sparse_vector_factory.py b/pinecone/data/sparse_values_factory.py similarity index 73% rename from pinecone/data/sparse_vector_factory.py rename to pinecone/data/sparse_values_factory.py index bc72c931a..4f3d2588c 100644 --- a/pinecone/data/sparse_vector_factory.py +++ b/pinecone/data/sparse_values_factory.py @@ -9,16 +9,21 @@ SparseValuesDictionaryExpectedError, ) -from pinecone.core.openapi.db_data.models import SparseValues +from .dataclasses import SparseValues +from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues class SparseValuesFactory: + """SparseValuesFactory is used to convert various types of user input into SparseValues objects used in generated request code.""" + @staticmethod - def build(input: Union[Dict, SparseValues]) -> SparseValues: + def build(input: Union[Dict, SparseValues]) -> OpenApiSparseValues: if input is None: return input - if isinstance(input, SparseValues): + if isinstance(input, OpenApiSparseValues): return input + if isinstance(input, SparseValues): + return OpenApiSparseValues(indices=input.indices, values=input.values) if not isinstance(input, Mapping): raise SparseValuesDictionaryExpectedError(input) if not {"indices", "values"}.issubset(input): @@ -31,7 +36,7 @@ def build(input: Union[Dict, SparseValues]) -> SparseValues: raise ValueError("Sparse values indices and values must have the same length") try: - return SparseValues(indices=indices, values=values) + return OpenApiSparseValues(indices=indices, values=values) except TypeError as e: raise SparseValuesTypeError() from e diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index 2723a9355..70f1c4c90 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -3,11 +3,16 @@ from collections.abc import Iterable, Mapping from typing import Union, Tuple, Dict -from ..utils import fix_tuple_length, convert_to_list +from ..utils import fix_tuple_length, convert_to_list, parse_non_empty_args from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS -from .sparse_vector_factory import SparseValuesFactory -from pinecone.core.openapi.db_data.models import Vector, SparseValues +from .sparse_values_factory import SparseValuesFactory + +from pinecone.core.openapi.db_data.models import ( + Vector as OpenApiVector, + SparseValues as OpenApiSparseValues, +) +from .dataclasses import Vector from .errors import ( VectorDictionaryMissingKeysError, @@ -18,10 +23,23 @@ class VectorFactory: + """VectorFactory is used to convert various types of input into vector objects used in generated request code.""" + @staticmethod - def build(item: Union[Vector, Tuple, Dict], check_type: bool = True) -> Vector: - if isinstance(item, Vector): + def build(item: Union[OpenApiVector, Tuple, Dict], check_type: bool = True) -> OpenApiVector: + if isinstance(item, OpenApiVector): return item + elif isinstance(item, Vector): + args = parse_non_empty_args( + [ + ("id", item.id), + ("values", item.values), + ("metadata", item.metadata), + ("sparse_values", SparseValuesFactory.build(item.sparse_values)), + ] + ) + + return OpenApiVector(**args) elif isinstance(item, tuple): return VectorFactory._tuple_to_vector(item, check_type) elif isinstance(item, Mapping): @@ -30,16 +48,16 @@ def build(item: Union[Vector, Tuple, Dict], check_type: bool = True) -> Vector: raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") @staticmethod - def _tuple_to_vector(item, check_type: bool) -> Vector: + def _tuple_to_vector(item, check_type: bool) -> OpenApiVector: if len(item) < 2 or len(item) > 3: raise VectorTupleLengthError(item) id, values, metadata = fix_tuple_length(item, 3) - if isinstance(values, SparseValues): + if isinstance(values, OpenApiSparseValues): raise ValueError( - "Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs." + "Sparse values are not supported in tuples. Please use either dicts or OpenApiVector objects as inputs." ) else: - return Vector( + return OpenApiVector( id=id, values=convert_to_list(values), metadata=metadata or {}, @@ -47,11 +65,16 @@ def _tuple_to_vector(item, check_type: bool) -> Vector: ) @staticmethod - def _dict_to_vector(item, check_type: bool) -> Vector: + def _dict_to_vector(item, check_type: bool) -> OpenApiVector: item_keys = set(item.keys()) if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): raise VectorDictionaryMissingKeysError(item) + if "sparse_values" not in item_keys and "values" not in item_keys: + raise ValueError( + "At least one of 'values' or 'sparse_values' must be provided in the vector dictionary." + ) + excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) if len(excessive_keys) > 0: raise VectorDictionaryExcessKeysError(item) @@ -59,6 +82,8 @@ def _dict_to_vector(item, check_type: bool) -> Vector: values = item.get("values") if "values" in item: item["values"] = convert_to_list(values) + else: + item["values"] = [] sparse_values = item.get("sparse_values") if sparse_values is None: @@ -71,7 +96,7 @@ def _dict_to_vector(item, check_type: bool) -> Vector: raise MetadataDictionaryExpectedError(item) try: - return Vector(**item, _check_type=check_type) + return OpenApiVector(**item, _check_type=check_type) except TypeError as e: if not isinstance(item["values"], Iterable) or not isinstance( item["values"].__iter__().__next__(), numbers.Real diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py index a027e8970..350047ca1 100644 --- a/pinecone/grpc/__init__.py +++ b/pinecone/grpc/__init__.py @@ -49,11 +49,11 @@ from .config import GRPCClientConfig from .future import PineconeGrpcFuture -from pinecone.core.grpc.protos.vector_service_pb2 import ( +from pinecone.data.dataclasses import Vector, SparseValues + +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( Vector as GRPCVector, SparseValues as GRPCSparseValues, - Vector, - SparseValues, DeleteResponse as GRPCDeleteResponse, ) diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index 170c17ace..fd6e1edc8 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -14,6 +14,7 @@ parse_stats_response, ) from .vector_factory_grpc import VectorFactoryGRPC +from .sparse_values_factory import SparseValuesFactory from pinecone.core.openapi.db_data.models import ( FetchResponse, @@ -21,7 +22,7 @@ IndexDescription as DescribeIndexStatsResponse, ) from pinecone.models.list_response import ListResponse as SimpleListResponse, Pagination -from pinecone.core.grpc.protos.vector_service_pb2 import ( +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( Vector as GRPCVector, QueryVector as GRPCQueryVector, UpsertRequest, @@ -36,9 +37,9 @@ UpdateResponse, SparseValues as GRPCSparseValues, ) -from pinecone import Vector as NonGRPCVector +from pinecone import Vector, SparseValues from pinecone.data.query_results_aggregator import QueryNamespacesResults, QueryResultsAggregator -from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub +from pinecone.core.grpc.protos.db_data_2025_01_pb2_grpc import VectorServiceStub from .base import GRPCIndexBase from .future import PineconeGrpcFuture @@ -62,7 +63,7 @@ def stub_class(self): def upsert( self, - vectors: Union[List[GRPCVector], List[NonGRPCVector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[GRPCVector], List[tuple], List[dict]], async_req: bool = False, namespace: Optional[str] = None, batch_size: Optional[int] = None, @@ -328,7 +329,9 @@ def query( filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, + sparse_vector: Optional[ + Union[SparseValues, GRPCSparseValues, SparseVectorTypedDict] + ] = None, async_req: Optional[bool] = False, **kwargs, ) -> Union[QueryResponse, PineconeGrpcFuture]: @@ -364,7 +367,7 @@ def query( include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. If omitted the server will use the default value of False [optional] sparse_vector: (Union[SparseValues, Dict[str, Union[List[float], List[int]]]]): sparse values of the query vector. - Expected to be either a GRPCSparseValues object or a dict of the form: + Expected to be either a SparseValues object or a dict of the form: {'indices': List[int], 'values': List[float]}, where the lists each have the same length. Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, @@ -379,7 +382,7 @@ def query( else: filter_struct = None - sparse_vector = self._parse_sparse_values_arg(sparse_vector) + sparse_vector = SparseValuesFactory.build(sparse_vector) args_dict = self._parse_non_empty_args( [ ("vector", vector), @@ -496,7 +499,7 @@ def update( set_metadata_struct = None timeout = kwargs.pop("timeout", None) - sparse_values = self._parse_sparse_values_arg(sparse_values) + sparse_values = SparseValuesFactory.build(sparse_values) args_dict = self._parse_non_empty_args( [ ("values", values), @@ -636,25 +639,3 @@ def describe_index_stats( @staticmethod 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} - - @staticmethod - def _parse_sparse_values_arg( - sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]], - ) -> Optional[GRPCSparseValues]: - if sparse_values is None: - return None - - if isinstance(sparse_values, GRPCSparseValues): - return sparse_values - - if ( - not isinstance(sparse_values, dict) - or "indices" not in sparse_values - or "values" not in sparse_values - ): - raise ValueError( - "Invalid sparse values argument. Expected a dict of: {'indices': List[int], 'values': List[float]}." - f"Received: {sparse_values}" - ) - - return GRPCSparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) diff --git a/pinecone/grpc/sparse_values_factory.py b/pinecone/grpc/sparse_values_factory.py index 433feb95a..dc4aa28b9 100644 --- a/pinecone/grpc/sparse_values_factory.py +++ b/pinecone/grpc/sparse_values_factory.py @@ -3,40 +3,42 @@ from ..utils import convert_to_list -from ..data import ( - SparseValuesTypeError, - SparseValuesMissingKeysError, - SparseValuesDictionaryExpectedError, -) +from ..data import SparseValuesTypeError, SparseValuesMissingKeysError -from pinecone.core.grpc.protos.vector_service_pb2 import SparseValues as GRPCSparseValues -from pinecone import SparseValues as NonGRPCSparseValues +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import SparseValues as GRPCSparseValues +from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues +from pinecone import SparseValues class SparseValuesFactory: @staticmethod - def build(input: Union[Dict, GRPCSparseValues, NonGRPCSparseValues]) -> GRPCSparseValues: + def build(input: Union[Dict, GRPCSparseValues, SparseValues]) -> GRPCSparseValues: if input is None: return input if isinstance(input, GRPCSparseValues): return input - if isinstance(input, NonGRPCSparseValues): - return GRPCSparseValues(indices=input.indices, values=input.values) - if not isinstance(input, Mapping): - raise SparseValuesDictionaryExpectedError(input) - if not {"indices", "values"}.issubset(input): - raise SparseValuesMissingKeysError(input) - - indices = SparseValuesFactory._convert_to_list(input.get("indices"), int) - values = SparseValuesFactory._convert_to_list(input.get("values"), float) - - if len(indices) != len(values): - raise ValueError("Sparse values indices and values must have the same length") - - try: - return GRPCSparseValues(indices=indices, values=values) - except TypeError as e: - raise SparseValuesTypeError() from e + if isinstance(input, SparseValues) or isinstance(input, OpenApiSparseValues): + return GRPCSparseValues( + indices=SparseValuesFactory._convert_to_list(input.indices, int), + values=SparseValuesFactory._convert_to_list(input.values, float), + ) + if isinstance(input, Mapping): + if not {"indices", "values"}.issubset(input): + raise SparseValuesMissingKeysError(input) + + indices = SparseValuesFactory._convert_to_list(input.get("indices"), int) + values = SparseValuesFactory._convert_to_list(input.get("values"), float) + + if len(indices) != len(values): + raise ValueError("Sparse values indices and values must have the same length") + + try: + return GRPCSparseValues(indices=indices, values=values) + except TypeError as e: + raise SparseValuesTypeError() from e + raise ValueError( + "SparseValuesFactory does not know how to handle input type {}".format(type(input)) + ) @staticmethod def _convert_to_list(input, expected_type): diff --git a/pinecone/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py index db4de0169..694bb71c8 100644 --- a/pinecone/grpc/vector_factory_grpc.py +++ b/pinecone/grpc/vector_factory_grpc.py @@ -16,23 +16,27 @@ ) from .sparse_values_factory import SparseValuesFactory -from pinecone.core.grpc.protos.vector_service_pb2 import ( +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( Vector as GRPCVector, SparseValues as GRPCSparseValues, ) -from pinecone import Vector as NonGRPCVector, SparseValues as NonGRPCSparseValues +from pinecone.core.openapi.db_data.models import ( + SparseValues as OpenApiSparseValues, + Vector as OpenApiVector, +) +from pinecone import Vector, SparseValues class VectorFactoryGRPC: + """This class is responsible for building GRPCVector objects from various input types.""" + @staticmethod - def build(item: Union[GRPCVector, NonGRPCVector, Tuple, Dict]) -> GRPCVector: + def build(item: Union[Vector, GRPCVector, Vector, Tuple, Dict]) -> GRPCVector: if isinstance(item, GRPCVector): return item - elif isinstance(item, NonGRPCVector): + elif isinstance(item, Vector) or isinstance(item, OpenApiVector): if item.sparse_values: - sv = GRPCSparseValues( - indices=item.sparse_values.indices, values=item.sparse_values.values - ) + sv = SparseValuesFactory.build(item.sparse_values) return GRPCVector( id=item.id, values=item.values, @@ -57,7 +61,11 @@ def _tuple_to_vector(item) -> GRPCVector: if len(item) < 2 or len(item) > 3: raise VectorTupleLengthError(item) id, values, metadata = fix_tuple_length(item, 3) - if isinstance(values, GRPCSparseValues) or isinstance(values, NonGRPCSparseValues): + if ( + isinstance(values, GRPCSparseValues) + or isinstance(values, SparseValues) + or isinstance(values, OpenApiSparseValues) + ): raise ValueError( "Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs." ) @@ -76,6 +84,11 @@ def _dict_to_vector(item) -> GRPCVector: if len(excessive_keys) > 0: raise VectorDictionaryExcessKeysError(item) + if "values" not in item and "sparse_values" not in item: + raise ValueError( + "At least one of 'values' or 'sparse_values' must be provided in the vector dictionary." + ) + values = item.get("values") if "values" in item: try: @@ -84,7 +97,7 @@ def _dict_to_vector(item) -> GRPCVector: raise TypeError("Column `values` is expected to be a list of floats") from e sparse_values = item.get("sparse_values") - if sparse_values is not None and not isinstance(sparse_values, GRPCSparseValues): + if sparse_values is not None: item["sparse_values"] = SparseValuesFactory.build(sparse_values) metadata = item.get("metadata") diff --git a/pinecone/utils/constants.py b/pinecone/utils/constants.py index b2461a4c9..b58d0b217 100644 --- a/pinecone/utils/constants.py +++ b/pinecone/utils/constants.py @@ -11,7 +11,7 @@ CLIENT_VERSION = __version__ CLIENT_ID = f"python-client-{CLIENT_VERSION}" -REQUIRED_VECTOR_FIELDS = {"id", "values"} -OPTIONAL_VECTOR_FIELDS = {"sparse_values", "metadata"} +REQUIRED_VECTOR_FIELDS = {"id"} +OPTIONAL_VECTOR_FIELDS = {"values", "sparse_values", "metadata"} SOURCE_TAG = "source_tag" diff --git a/pinecone/utils/docslinks.py b/pinecone/utils/docslinks.py index 98e7442f5..a0bd9d9ca 100644 --- a/pinecone/utils/docslinks.py +++ b/pinecone/utils/docslinks.py @@ -1,4 +1,9 @@ +from pinecone.core.openapi.db_control import API_VERSION + docslinks = { "GITHUB_REPO": "https://github.com/pinecone-io/pinecone-python-client", "LANGCHAIN_IMPORT_KB_ARTICLE": "https://docs.pinecone.io/troubleshooting/pinecone-attribute-errors-with-langchain", + "API_DESCRIBE_INDEX": "https://docs.pinecone.io/reference/api/{}/control-plane/describe_index".format( + API_VERSION + ), } diff --git a/tests/integration/control/pod/test_collections.py b/tests/integration/control/pod/test_collections.py index 46e659361..53cc2ca5e 100644 --- a/tests/integration/control/pod/test_collections.py +++ b/tests/integration/control/pod/test_collections.py @@ -89,7 +89,6 @@ def test_index_to_collection_to_index_happy_path( # Verify stats reflect the vectors present in the collection stats = new_index.describe_index_stats() - print(stats) assert stats.total_vector_count == num_vectors # Verify the vectors from the collection can be fetched diff --git a/tests/integration/control/serverless/conftest.py b/tests/integration/control/serverless/conftest.py index ee1347c07..7a3abcd78 100644 --- a/tests/integration/control/serverless/conftest.py +++ b/tests/integration/control/serverless/conftest.py @@ -1,4 +1,3 @@ -import os import pytest import random import time @@ -105,17 +104,3 @@ def cleanup(client, index_name): client.delete_index(index_name, -1) except Exception: pass - - -@pytest.fixture(autouse=True, scope="session") -def cleanup_all(): - yield - - client = Pinecone(additional_headers={"sdk-test-suite": "pinecone-python-client"}) - for index in client.list_indexes(): - buildNumber = os.getenv("GITHUB_BUILD_NUMBER") - if index.name.startswith(buildNumber): - try: - delete_with_retry(client, index.name) - except Exception: - pass 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 33755e5e3..f123e280a 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 @@ -11,10 +11,21 @@ def test_create_index(self, client, create_sl_index_params): assert desc.dimension == dimension assert desc.metric == "cosine" assert desc.deletion_protection == "disabled" # default value + assert desc.vector_type == "dense" # default value @pytest.mark.parametrize("metric", ["cosine", "euclidean", "dotproduct"]) - def test_create_index_with_metric(self, client, create_sl_index_params, metric): + def test_create_default_index_with_metric(self, client, create_sl_index_params, metric): create_sl_index_params["metric"] = metric client.create_index(**create_sl_index_params) desc = client.describe_index(create_sl_index_params["name"]) assert desc.metric == metric + assert desc.vector_type == "dense" + + @pytest.mark.parametrize("metric", ["cosine", "euclidean", "dotproduct"]) + def test_create_dense_index_with_metric(self, client, create_sl_index_params, metric): + create_sl_index_params["metric"] = metric + create_sl_index_params["vector_type"] = "dense" + client.create_index(**create_sl_index_params) + desc = client.describe_index(create_sl_index_params["name"]) + assert desc.metric == metric + assert desc.vector_type == "dense" diff --git a/tests/integration/control/serverless/test_sparse_index.py b/tests/integration/control/serverless/test_sparse_index.py new file mode 100644 index 000000000..b07bba626 --- /dev/null +++ b/tests/integration/control/serverless/test_sparse_index.py @@ -0,0 +1,73 @@ +import pytest +from pinecone.exceptions import PineconeApiException + + +class TestSparseIndex: + def test_create_sparse_index_with_metric(self, client, create_sl_index_params): + create_sl_index_params["metric"] = "dotproduct" + + create_sl_index_params["vector_type"] = "sparse" + del create_sl_index_params["dimension"] + + client.create_index(**create_sl_index_params) + desc = client.describe_index(create_sl_index_params["name"]) + assert desc.metric == "dotproduct" + assert desc.vector_type == "sparse" + assert desc.dimension is None + assert desc.deletion_protection == "disabled" # default value + + for i in client.list_indexes(): + if i.name == create_sl_index_params["name"]: + assert i.metric == "dotproduct" + assert i.vector_type == "sparse" + assert i.dimension is None + assert i.deletion_protection == "disabled" + break + else: + assert i.vector_type is not None + + def test_sparse_index_deletion_protection(self, client, create_sl_index_params): + create_sl_index_params["metric"] = "dotproduct" + create_sl_index_params["vector_type"] = "sparse" + create_sl_index_params["deletion_protection"] = "enabled" + del create_sl_index_params["dimension"] + + client.create_index(**create_sl_index_params) + + desc = client.describe_index(create_sl_index_params["name"]) + assert desc.metric == "dotproduct" + assert desc.vector_type == "sparse" + assert desc.dimension is None + assert desc.deletion_protection == "enabled" + + with pytest.raises(PineconeApiException) as e: + client.delete_index(create_sl_index_params["name"], -1) + assert "Deletion protection is enabled for this index" in str(e.value) + + client.configure_index(create_sl_index_params["name"], deletion_protection="disabled") + + desc2 = client.describe_index(create_sl_index_params["name"]) + assert desc2.deletion_protection == "disabled" + + client.delete_index(create_sl_index_params["name"], -1) + + +class TestSparseIndexErrorCases: + def test_exception_when_passing_dimension(self, client, create_sl_index_params): + create_sl_index_params["metric"] = "dotproduct" + create_sl_index_params["dimension"] = 10 + create_sl_index_params["vector_type"] = "sparse" + + with pytest.raises(ValueError) as e: + client.create_index(**create_sl_index_params) + assert "dimension should not be specified for sparse indexes" in str(e.value) + + @pytest.mark.parametrize("metric", ["cosine", "euclidean"]) + def test_sparse_only_supports_dotproduct(self, client, create_sl_index_params, metric): + create_sl_index_params["metric"] = metric + create_sl_index_params["vector_type"] = "sparse" + del create_sl_index_params["dimension"] + + with pytest.raises(PineconeApiException) as e: + client.create_index(**create_sl_index_params) + assert "Sparse vector indexes must use dotproduct" in str(e.value) diff --git a/tests/integration/data/test_upsert.py b/tests/integration/data/test_upsert.py deleted file mode 100644 index cc87dbce2..000000000 --- a/tests/integration/data/test_upsert.py +++ /dev/null @@ -1,87 +0,0 @@ -import pytest -import os -from pinecone import Vector, SparseValues -from ..helpers import poll_stats_for_namespace -from .utils import embedding_values - - -@pytest.mark.parametrize("use_nondefault_namespace", [True, False]) -def test_upsert_to_namespace(idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" - - # Upsert with tuples - idx.upsert( - vectors=[("1", embedding_values()), ("2", embedding_values()), ("3", embedding_values())], - namespace=target_namespace, - ) - - # Upsert with objects - idx.upsert( - vectors=[ - Vector(id="4", values=embedding_values()), - Vector(id="5", values=embedding_values()), - Vector(id="6", values=embedding_values()), - ], - namespace=target_namespace, - ) - - # Upsert with dict - idx.upsert( - vectors=[ - {"id": "7", "values": embedding_values()}, - {"id": "8", "values": embedding_values()}, - {"id": "9", "values": embedding_values()}, - ], - namespace=target_namespace, - ) - - poll_stats_for_namespace(idx, target_namespace, 9) - - # Check the vector count reflects some data has been upserted - stats = idx.describe_index_stats() - assert stats.total_vector_count >= 9 - assert stats.namespaces[target_namespace].vector_count == 9 - - -@pytest.mark.parametrize("use_nondefault_namespace", [True, False]) -@pytest.mark.skipif( - os.getenv("METRIC") != "dotproduct", reason="Only metric=dotprodouct indexes support hybrid" -) -def test_upsert_to_namespace_with_sparse_embedding_values(idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" - - # Upsert with sparse values object - idx.upsert( - vectors=[ - Vector( - id="1", - values=embedding_values(), - sparse_values=SparseValues(indices=[0, 1], values=embedding_values()), - ) - ], - namespace=target_namespace, - ) - - # Upsert with sparse values dict - idx.upsert( - vectors=[ - { - "id": "2", - "values": embedding_values(), - "sparse_values": {"indices": [0, 1], "values": embedding_values()}, - }, - { - "id": "3", - "values": embedding_values(), - "sparse_values": {"indices": [0, 1], "values": embedding_values()}, - }, - ], - namespace=target_namespace, - ) - - poll_stats_for_namespace(idx, target_namespace, 9) - - # Check the vector count reflects some data has been upserted - stats = idx.describe_index_stats() - assert stats.total_vector_count >= 9 - assert stats.namespaces[target_namespace].vector_count == 9 diff --git a/tests/integration/data/test_upsert_dense.py b/tests/integration/data/test_upsert_dense.py new file mode 100644 index 000000000..e36eb2963 --- /dev/null +++ b/tests/integration/data/test_upsert_dense.py @@ -0,0 +1,47 @@ +import pytest +from pinecone import Vector +from ..helpers import poll_stats_for_namespace +from .utils import embedding_values + + +class TestUpsertDense: + @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) + def test_upsert_to_namespace(self, idx, namespace, use_nondefault_namespace): + target_namespace = namespace if use_nondefault_namespace else "" + + # Upsert with tuples + idx.upsert( + vectors=[ + ("1", embedding_values()), + ("2", embedding_values()), + ("3", embedding_values()), + ], + namespace=target_namespace, + ) + + # Upsert with objects + idx.upsert( + vectors=[ + Vector(id="4", values=embedding_values()), + Vector(id="5", values=embedding_values()), + Vector(id="6", values=embedding_values()), + ], + namespace=target_namespace, + ) + + # Upsert with dict + idx.upsert( + vectors=[ + {"id": "7", "values": embedding_values()}, + {"id": "8", "values": embedding_values()}, + {"id": "9", "values": embedding_values()}, + ], + namespace=target_namespace, + ) + + poll_stats_for_namespace(idx, target_namespace, 9) + + # Check the vector count reflects some data has been upserted + stats = idx.describe_index_stats() + assert stats.total_vector_count >= 9 + assert stats.namespaces[target_namespace].vector_count == 9 diff --git a/tests/integration/data/test_upsert_hybrid.py b/tests/integration/data/test_upsert_hybrid.py new file mode 100644 index 000000000..4d1b640e1 --- /dev/null +++ b/tests/integration/data/test_upsert_hybrid.py @@ -0,0 +1,52 @@ +import pytest +import os +from pinecone import Vector, SparseValues +from ..helpers import poll_stats_for_namespace +from .utils import embedding_values + + +@pytest.mark.skipif( + os.getenv("METRIC") != "dotproduct", reason="Only metric=dotprodouct indexes support hybrid" +) +class TestUpsertHybrid: + @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) + def test_upsert_to_namespace_with_sparse_embedding_values( + self, idx, namespace, use_nondefault_namespace + ): + target_namespace = namespace if use_nondefault_namespace else "" + + # Upsert with sparse values object + idx.upsert( + vectors=[ + Vector( + id="1", + values=embedding_values(), + sparse_values=SparseValues(indices=[0, 1], values=embedding_values()), + ) + ], + namespace=target_namespace, + ) + + # Upsert with sparse values dict + idx.upsert( + vectors=[ + { + "id": "2", + "values": embedding_values(), + "sparse_values": {"indices": [0, 1], "values": embedding_values()}, + }, + { + "id": "3", + "values": embedding_values(), + "sparse_values": {"indices": [0, 1], "values": embedding_values()}, + }, + ], + namespace=target_namespace, + ) + + poll_stats_for_namespace(idx, target_namespace, 9) + + # Check the vector count reflects some data has been upserted + stats = idx.describe_index_stats() + assert stats.total_vector_count >= 9 + assert stats.namespaces[target_namespace].vector_count == 9 diff --git a/tests/integration/data/test_upsert_sparse.py b/tests/integration/data/test_upsert_sparse.py new file mode 100644 index 000000000..2842bbfe4 --- /dev/null +++ b/tests/integration/data/test_upsert_sparse.py @@ -0,0 +1,91 @@ +import pytest +import random +from pinecone import Vector, SparseValues +from ..helpers import poll_stats_for_namespace +from .utils import embedding_values + +import logging + +logger = logging.getLogger(__name__) + + +class TestUpsertSparse: + @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) + def test_upsert_sparse_to_namespace(self, sparse_idx, use_nondefault_namespace, namespace): + target_namespace = namespace if use_nondefault_namespace else "" + + # Upsert with objects + sparse_idx.upsert( + vectors=[ + Vector( + id=str(i), + sparse_values=SparseValues( + indices=[i, random.randint(2000, 4000)], values=embedding_values(2) + ), + ) + for i in range(50) + ], + namespace=target_namespace, + ) + + # Upsert with dict + sparse_idx.upsert( + vectors=[ + { + "id": str(i), + "sparse_values": { + "indices": [i, random.randint(2000, 4000)], + "values": embedding_values(2), + }, + } + for i in range(51, 100) + ], + namespace=target_namespace, + ) + + # Upsert with mixed types, dict with SparseValues object + sparse_idx.upsert( + vectors=[ + { + "id": str(i), + "sparse_values": SparseValues( + indices=[i, random.randint(2000, 4000)], values=embedding_values(2) + ), + } + for i in range(101, 150) + ], + namespace=target_namespace, + ) + + # Upsert with mixed types, object with dict + sparse_idx.upsert( + vectors=[ + Vector( + id=str(i), + sparse_values={ + "indices": [i, random.randint(2000, 4000)], + "values": embedding_values(2), + }, + ) + for i in range(151, 200) + ], + namespace=target_namespace, + ) + + poll_stats_for_namespace(sparse_idx, target_namespace, 99, max_sleep=300) + + results = sparse_idx.query( + sparse_vector={"indices": [5, 6, 7, 8, 9], "values": embedding_values(5)}, + namespace=target_namespace, + top_k=5, + ) + + assert len(results.matches) == 5 + + # Can query with SparseValues object + results2 = sparse_idx.query( + sparse_vector=SparseValues(indices=[5, 6, 7, 8, 9], values=embedding_values(5)), + namespace=target_namespace, + top_k=5, + ) + assert len(results2.matches) == 5 diff --git a/tests/integration/helpers/helpers.py b/tests/integration/helpers/helpers.py index 9adb01aca..d22f4b8ed 100644 --- a/tests/integration/helpers/helpers.py +++ b/tests/integration/helpers/helpers.py @@ -3,9 +3,12 @@ import time import random import string +import logging from typing import Any from datetime import datetime +logger = logging.getLogger(__name__) + def random_string(length): return "".join(random.choice(string.ascii_lowercase) for i in range(length)) @@ -65,7 +68,7 @@ def poll_stats_for_namespace( total_time = 0 done = False while not done: - print( + logger.debug( f'Waiting for namespace "{namespace}" to have vectors. Total time waited: {total_time} seconds' ) stats = idx.describe_index_stats() @@ -87,9 +90,11 @@ def poll_fetch_for_ids_in_namespace(idx, ids, namespace): total_time = 0 done = False while not done: - print(f'Attempting to fetch from "{namespace}". Total time waited: {total_time} seconds') + logger.debug( + f'Attempting to fetch from "{namespace}". Total time waited: {total_time} seconds' + ) results = idx.fetch(ids=ids, namespace=namespace) - print(results) + logger.debug(results) all_present = all(key in results.vectors for key in ids) if all_present: diff --git a/tests/unit/data/test_datetime_parsing.py b/tests/unit/data/test_datetime_parsing.py index 43e67ae90..4e342dccf 100644 --- a/tests/unit/data/test_datetime_parsing.py +++ b/tests/unit/data/test_datetime_parsing.py @@ -1,4 +1,5 @@ -from pinecone import Vector, Config +from pinecone import Config +from pinecone.core.openapi.db_data.models import Vector class TestDatetimeConversion: diff --git a/tests/unit/data/test_vector_factory.py b/tests/unit/data/test_vector_factory.py index e7b7199d1..52fd1eac9 100644 --- a/tests/unit/data/test_vector_factory.py +++ b/tests/unit/data/test_vector_factory.py @@ -4,13 +4,17 @@ from pinecone.data.vector_factory import VectorFactory from pinecone import Vector, SparseValues, ListConversionException +from pinecone.core.openapi.db_data.models import ( + Vector as OpenApiVector, + SparseValues as OpenApiSparseValues, +) -class TestVectorFactory: +class TestVectorFactory_DenseVectors: def test_build_when_returns_vector_unmodified(self): vec = Vector(id="1", values=[0.1, 0.2, 0.3]) - assert VectorFactory.build(vec) == vec - assert VectorFactory.build(vec).__class__ == Vector + assert VectorFactory.build(vec) == OpenApiVector(id="1", values=[0.1, 0.2, 0.3]) + assert VectorFactory.build(vec).__class__ == OpenApiVector @pytest.mark.parametrize( "values_array", [[0.1, 0.2, 0.3], np.array([0.1, 0.2, 0.3]), pd.array([0.1, 0.2, 0.3])] @@ -18,7 +22,7 @@ def test_build_when_returns_vector_unmodified(self): def test_build_when_tuple_with_two_values(self, values_array): tup = ("1", values_array) actual = VectorFactory.build(tup) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={}) + expected = OpenApiVector(id="1", values=[0.1, 0.2, 0.3], metadata={}) assert actual == expected @pytest.mark.parametrize( @@ -27,7 +31,7 @@ def test_build_when_tuple_with_two_values(self, values_array): def test_build_when_tuple_with_three_values(self, values_array): tup = ("1", values_array, {"genre": "comedy"}) actual = VectorFactory.build(tup) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + expected = OpenApiVector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) assert actual == expected @pytest.mark.parametrize( @@ -63,7 +67,7 @@ def test_build_when_tuple_too_short(self): def test_build_when_dict(self, values_array): d = {"id": "1", "values": values_array, "metadata": {"genre": "comedy"}} actual = VectorFactory.build(d) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + expected = OpenApiVector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) assert actual == expected def test_build_when_dict_missing_required_fields(self): @@ -81,6 +85,8 @@ def test_build_when_dict_excess_keys(self): } VectorFactory.build(d) + +class TestVectorFactory_HybridVectors: def test_build_when_dict_sparse_values(self): d = { "id": "1", @@ -89,11 +95,11 @@ def test_build_when_dict_sparse_values(self): "sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}, } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -105,11 +111,11 @@ def test_build_when_dict_sparse_values_when_SparseValues(self): "sparse_values": SparseValues(indices=[0, 2], values=[0.1, 0.3]), } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -177,11 +183,11 @@ def test_build_when_dict_sparse_values_when_values_is_ndarray(self): "sparse_values": {"indices": [0, 2], "values": np.array([0.1, 0.3])}, } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -193,11 +199,11 @@ def test_build_when_dict_sparse_values_when_indices_is_pandas_IntegerArray(self) "sparse_values": {"indices": pd.array([0, 2]), "values": [0.1, 0.3]}, } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -209,11 +215,11 @@ def test_build_when_dict_sparse_values_when_values_is_pandas_FloatingArray(self) "sparse_values": {"indices": [0, 2], "values": pd.array([0.1, 0.3])}, } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -225,11 +231,11 @@ def test_build_when_dict_sparse_values_when_indices_is_ndarray(self): "sparse_values": {"indices": np.array([0, 2]), "values": [0.1, 0.3]}, } actual = VectorFactory.build(d) - expected = Vector( + expected = OpenApiVector( id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}, - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -245,5 +251,74 @@ def test_build_when_sparse_values_is_None(self): "sparse_values": None, } actual = VectorFactory.build(d) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + expected = OpenApiVector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + assert actual == expected + + +class TestVectorFactory_SparseVectors: + def test_when_sparse_only_it_sets_empty_values_obj(self): + o = Vector(id="1", sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + actual = VectorFactory.build(o) + expected = OpenApiVector( + id="1", values=[], sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]) + ) + assert actual == expected + + def test_sparse_when_dict(self): + d = {"id": "1", "sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}} + actual = VectorFactory.build(d) + expected = OpenApiVector( + id="1", values=[], sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]) + ) assert actual == expected + + def test_sparse_when_dict_with_object(self): + d = {"id": "1", "sparse_values": SparseValues(indices=[0, 2], values=[0.1, 0.3])} + actual = VectorFactory.build(d) + expected = OpenApiVector( + id="1", values=[], sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]) + ) + assert actual == expected + + def test_sparse_when_object_with_dict(self): + o = Vector(id="1", sparse_values={"indices": [0, 2], "values": [0.1, 0.3]}) + actual = VectorFactory.build(o) + expected = OpenApiVector( + id="1", values=[], sparse_values=OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]) + ) + assert actual == expected + + def test_when_passing_openapi_objects_should_be_unmodified(self): + """Not really expecting this, but it's possible somebody could do it.""" + o = OpenApiVector(id="1", values=[0.1, 0.2, 0.3]) + actual = VectorFactory.build(o) + expected = OpenApiVector(id="1", values=[0.1, 0.2, 0.3]) + assert actual == expected + + def test_sparse_dict_when_missing_keys(self): + with pytest.raises( + ValueError, match="Missing required keys in data in column `sparse_values`" + ): + d = {"id": "1", "sparse_values": {}} + VectorFactory.build(d) + + +class TestVectorFactory_EdgeCases: + def test_missing_values_and_sparse_values_dict(self): + with pytest.raises( + ValueError, + match="At least one of 'values' or 'sparse_values' must be provided in the vector dictionary.", + ): + VectorFactory.build({"id": "1"}) + + def test_missing_values_and_sparse_values_obj(self): + with pytest.raises( + ValueError, match="The values and sparse_values fields cannot both be empty" + ): + VectorFactory.build(Vector(id="1")) + + def test_missing_id(self): + with pytest.raises(ValueError, match="Vector dictionary is missing required fields"): + VectorFactory.build({"values": [0.1, 0.2, 0.3]}) + with pytest.raises(ValueError, match="Vector dictionary is missing required fields"): + VectorFactory.build({"sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}}) diff --git a/tests/unit_grpc/test_grpc_index_describe_index_stats.py b/tests/unit_grpc/test_grpc_index_describe_index_stats.py index 24f8dcf7b..e37c6d041 100644 --- a/tests/unit_grpc/test_grpc_index_describe_index_stats.py +++ b/tests/unit_grpc/test_grpc_index_describe_index_stats.py @@ -1,6 +1,6 @@ from pinecone import Config from pinecone.grpc import GRPCIndex -from pinecone.core.grpc.protos.vector_service_pb2 import DescribeIndexStatsRequest +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import DescribeIndexStatsRequest from pinecone.grpc.utils import dict_to_proto_struct diff --git a/tests/unit_grpc/test_grpc_index_fetch.py b/tests/unit_grpc/test_grpc_index_fetch.py index 620acfbb1..b87b2611f 100644 --- a/tests/unit_grpc/test_grpc_index_fetch.py +++ b/tests/unit_grpc/test_grpc_index_fetch.py @@ -1,6 +1,6 @@ from pinecone import Config from pinecone.grpc import GRPCIndex -from pinecone.core.grpc.protos.vector_service_pb2 import FetchRequest +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import FetchRequest class TestGrpcIndexFetch: diff --git a/tests/unit_grpc/test_grpc_index_query.py b/tests/unit_grpc/test_grpc_index_query.py index 86e0f6a26..a93fa9fa1 100644 --- a/tests/unit_grpc/test_grpc_index_query.py +++ b/tests/unit_grpc/test_grpc_index_query.py @@ -2,7 +2,7 @@ from pinecone import Config from pinecone.grpc import GRPCIndex -from pinecone.core.grpc.protos.vector_service_pb2 import QueryRequest +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import QueryRequest from pinecone.grpc.utils import dict_to_proto_struct diff --git a/tests/unit_grpc/test_grpc_index_update.py b/tests/unit_grpc/test_grpc_index_update.py index 978e06aab..59e65d8f1 100644 --- a/tests/unit_grpc/test_grpc_index_update.py +++ b/tests/unit_grpc/test_grpc_index_update.py @@ -1,6 +1,6 @@ from pinecone import Config from pinecone.grpc import GRPCIndex -from pinecone.core.grpc.protos.vector_service_pb2 import UpdateRequest +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import UpdateRequest from pinecone.grpc.utils import dict_to_proto_struct diff --git a/tests/unit_grpc/test_grpc_index_upsert.py b/tests/unit_grpc/test_grpc_index_upsert.py index 2eba655e4..194b4d864 100644 --- a/tests/unit_grpc/test_grpc_index_upsert.py +++ b/tests/unit_grpc/test_grpc_index_upsert.py @@ -6,7 +6,7 @@ from pinecone import Config from pinecone.grpc import GRPCIndex -from pinecone.core.grpc.protos.vector_service_pb2 import ( +from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( Vector, UpsertRequest, UpsertResponse, @@ -284,8 +284,6 @@ def test_upsert_dict_negative(self, mocker, vals1, vals2, md2): ("values", 0.5), ("metadata", np.nan), ("metadata", ["key1", "key2"]), - ("sparse_values", "cat"), - ("sparse_values", []), ], ) def test_upsert_dict_with_invalid_values( @@ -306,6 +304,25 @@ def test_upsert_dict_with_invalid_values( self.index.upsert([dict1]) assert key in str(e.value) + @pytest.mark.parametrize("key,new_val", [("sparse_values", "cat"), ("sparse_values", [])]) + def test_upsert_dict_with_invalid_sparse_values_type( + self, mocker, key, new_val, vals1, md1, sparse_indices_1, sparse_values_1 + ): + mocker.patch.object(self.index.runner, "run", autospec=True) + + full_dict1 = { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + "metadata": md1, + } + + dict1 = deepcopy(full_dict1) + dict1[key] = new_val + with pytest.raises(ValueError) as e: + self.index.upsert([dict1]) + assert "SparseValuesFactory does not know how to handle input type" in str(e.value) + @pytest.mark.parametrize("key,new_val", [("id", 4.2), ("id", ["vec1"])]) def test_upsert_dict_with_invalid_ids( self, mocker, key, new_val, vals1, md1, sparse_indices_1, sparse_values_1 @@ -343,7 +360,7 @@ def test_upsert_dict_with_invalid_sparse_values( dict1 = deepcopy(full_dict1) dict1["sparse_values"][key] = new_val - with pytest.raises(TypeError) as e: + with pytest.raises(ValueError) as e: self.index.upsert([dict1]) assert "sparse" in str(e.value) assert key in str(e.value) diff --git a/tests/unit_grpc/test_sparse_values_factory.py b/tests/unit_grpc/test_sparse_values_factory.py index 4b3066f5c..a602ec9b7 100644 --- a/tests/unit_grpc/test_sparse_values_factory.py +++ b/tests/unit_grpc/test_sparse_values_factory.py @@ -1,6 +1,7 @@ import pytest -from pinecone.grpc import SparseValues as GRPCSparseValues -from pinecone import SparseValues as NonGRPCSparseValues +from pinecone.grpc import GRPCSparseValues +from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues +from pinecone import SparseValues import numpy as np import pandas as pd @@ -21,11 +22,18 @@ def test_build_when_passed_GRPCSparseValues(self): actual = SparseValuesFactory.build(sv) assert actual == sv - def test_build_when_passed_NonGRPCSparseValues(self): + def test_build_when_given_SparseValues(self): + sv = SparseValues(indices=[0, 2], values=[0.1, 0.3]) + actual = SparseValuesFactory.build(sv) + expected = GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]) + assert isinstance(actual, GRPCSparseValues) + assert actual == expected + + def test_build_when_passed_OpenApiSparseValues(self): """ - Convert when given NonGRPCSparseValues + Convert when given OpenApiSparseValues """ - sv = NonGRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]) + sv = OpenApiSparseValues(indices=[0, 2], values=[0.1, 0.3]) actual = SparseValuesFactory.build(sv) expected = GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]) assert actual == expected diff --git a/tests/unit_grpc/test_vector_factory_grpc.py b/tests/unit_grpc/test_vector_factory_grpc.py index 11cfb401d..43ef21d9f 100644 --- a/tests/unit_grpc/test_vector_factory_grpc.py +++ b/tests/unit_grpc/test_vector_factory_grpc.py @@ -4,49 +4,44 @@ from pinecone.grpc.vector_factory_grpc import VectorFactoryGRPC -from pinecone.grpc import Vector, SparseValues +from pinecone.grpc import GRPCVector, GRPCSparseValues +from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues from pinecone.grpc.utils import dict_to_proto_struct -from pinecone import Vector as NonGRPCVector, SparseValues as NonGRPCSparseValues +from pinecone import Vector, SparseValues -class TestVectorFactoryGRPC: +class TestVectorFactoryGRPC_DenseVectors: def test_build_when_returns_vector_unmodified(self): - vec = Vector(id="1", values=[0.1, 0.2, 0.3]) + vec = GRPCVector(id="1", values=[0.1, 0.2, 0.3]) assert VectorFactoryGRPC.build(vec) == vec - assert VectorFactoryGRPC.build(vec).__class__ == Vector + assert VectorFactoryGRPC.build(vec).__class__ == GRPCVector + + def test_build_converts_vector(self): + vec = Vector(id="1", values=[0.1, 0.2, 0.3]) + assert VectorFactoryGRPC.build(vec).__class__ == GRPCVector + assert VectorFactoryGRPC.build(vec) == GRPCVector( + id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({}) + ) def test_build_when_nongrpc_vector_it_converts(self): - vec = NonGRPCVector(id="1", values=[0.1, 0.2, 0.3]) - assert VectorFactoryGRPC.build(vec) == Vector( + vec = Vector(id="1", values=[0.1, 0.2, 0.3]) + assert VectorFactoryGRPC.build(vec) == GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({}) ) def test_build_when_nongrpc_vector_with_metadata_it_converts(self): - vec = NonGRPCVector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) - assert VectorFactoryGRPC.build(vec) == Vector( + vec = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + assert VectorFactoryGRPC.build(vec) == GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) ) - def test_build_when_nongrpc_vector_with_sparse_values_it_converts(self): - vec = NonGRPCVector( - id="1", - values=[0.1, 0.2, 0.3], - sparse_values=NonGRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), - ) - assert VectorFactoryGRPC.build(vec) == Vector( - id="1", - values=[0.1, 0.2, 0.3], - metadata=dict_to_proto_struct({}), - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), - ) - @pytest.mark.parametrize( "values_array", [[0.1, 0.2, 0.3], np.array([0.1, 0.2, 0.3]), pd.array([0.1, 0.2, 0.3])] ) def test_build_when_tuple_with_two_values(self, values_array): tup = ("1", values_array) actual = VectorFactoryGRPC.build(tup) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + expected = GRPCVector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) assert actual == expected @pytest.mark.parametrize( @@ -68,19 +63,27 @@ def test_build_when_tuple_values_must_be_list(self, vector_tup): def test_build_when_tuple_with_three_values(self, values_array): tup = ("1", values_array, {"genre": "comedy"}) actual = VectorFactoryGRPC.build(tup) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) ) assert actual == expected - @pytest.mark.parametrize("sv_klass", [SparseValues, NonGRPCSparseValues]) - def test_build_vector_with_tuple_with_sparse_values(self, sv_klass): - tup = ("1", sv_klass(indices=[0, 2], values=[0.1, 0.3])) - with pytest.raises( - ValueError, - match="Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs.", - ): - VectorFactoryGRPC.build(tup) + def test_build_with_dict_no_metadata(self): + d = {"id": "1", "values": [0.1, 0.2, 0.3]} + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + assert actual == expected + + @pytest.mark.parametrize( + "metadata", [{"genre": "comedy"}, dict_to_proto_struct({"genre": "comedy"})] + ) + def test_build_when_dict_with_metadata2(self, metadata): + d = {"id": "1", "values": [0.1, 0.2, 0.3], "metadata": metadata} + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) + ) + assert actual == expected def test_build_when_tuple_errors_when_additional_fields(self): with pytest.raises(ValueError, match="Found a tuple of length 4 which is not supported"): @@ -92,23 +95,80 @@ def test_build_when_tuple_too_short(self): tup = ("1",) VectorFactoryGRPC.build(tup) - @pytest.mark.parametrize( - "metadata", [{"genre": "comedy"}, dict_to_proto_struct({"genre": "comedy"})] - ) - def test_build_when_dict(self, metadata): - d = {"id": "1", "values": [0.1, 0.2, 0.3], "metadata": metadata} + @pytest.mark.parametrize("input_values", [pd.array([0.1, 0.2, 0.3]), np.array([0.1, 0.2, 0.3])]) + def test_build_when_dict_with_special_values(self, input_values): + d = {"id": "1", "values": input_values, "metadata": {"genre": "comedy"}} actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) ) assert actual == expected - def test_build_with_dict_no_metadata(self): - d = {"id": "1", "values": [0.1, 0.2, 0.3]} + @pytest.mark.parametrize("input_values", [pd.array([0.1, 0.2, 0.3]), np.array([0.1, 0.2, 0.3])]) + def test_build_when_Vector_with_special_values(self, input_values): + d = Vector(**{"id": "1", "values": input_values, "metadata": {"genre": "comedy"}}) + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) + ) + assert actual == expected + + @pytest.mark.parametrize("input_values", [pd.array([0.1, 0.2, 0.3]), np.array([0.1, 0.2, 0.3])]) + def test_build_when_Vector_with_special_sparse_values(self, input_values): + d = Vector( + id="1", + values=input_values, + sparse_values=SparseValues(indices=[0, 1, 2], values=input_values), + metadata={"genre": "comedy"}, + ) actual = VectorFactoryGRPC.build(d) - expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + expected = GRPCVector( + id="1", + values=[0.1, 0.2, 0.3], + sparse_values=GRPCSparseValues(indices=[0, 1, 2], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) assert actual == expected + def test_build_when_dict_missing_required_fields(self): + with pytest.raises(ValueError, match="Vector dictionary is missing required fields"): + d = {"values": [0.1, 0.2, 0.3]} + VectorFactoryGRPC.build(d) + + def test_build_when_dict_excess_keys(self): + with pytest.raises(ValueError, match="Found excess keys in the vector dictionary"): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "extra": "field", + } + VectorFactoryGRPC.build(d) + + +class TestVectorFactoryGRPC_HybridVectors: + def test_build_when_nongrpc_vector_with_sparse_values_it_converts(self): + vec = Vector( + id="1", + values=[0.1, 0.2, 0.3], + sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + ) + assert VectorFactoryGRPC.build(vec) == GRPCVector( + id="1", + values=[0.1, 0.2, 0.3], + metadata=dict_to_proto_struct({}), + sparse_values=GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), + ) + + @pytest.mark.parametrize("sv_klass", [SparseValues, OpenApiSparseValues, GRPCSparseValues]) + def test_build_vector_with_tuple_with_sparse_values(self, sv_klass): + tup = ("1", sv_klass(indices=[0, 2], values=[0.1, 0.3])) + with pytest.raises( + ValueError, + match="Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs.", + ): + VectorFactoryGRPC.build(tup) + def test_build_when_dict_with_sparse_values_dict(self): d = { "id": "1", @@ -117,15 +177,15 @@ def test_build_when_dict_with_sparse_values_dict(self): "sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}, } actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}), - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected - @pytest.mark.parametrize("sv_klass", [SparseValues, NonGRPCSparseValues]) + @pytest.mark.parametrize("sv_klass", [SparseValues, OpenApiSparseValues, GRPCSparseValues]) def test_build_with_dict_with_sparse_values_object(self, sv_klass): d = { "id": "1", @@ -134,38 +194,14 @@ def test_build_with_dict_with_sparse_values_object(self, sv_klass): "sparse_values": sv_klass(indices=[0, 2], values=[0.1, 0.3]), } actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}), - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), - ) - assert actual == expected - - @pytest.mark.parametrize("input_values", [pd.array([0.1, 0.2, 0.3]), np.array([0.1, 0.2, 0.3])]) - def test_build_when_dict_with_special_values(self, input_values): - d = {"id": "1", "values": input_values, "metadata": {"genre": "comedy"}} - actual = VectorFactoryGRPC.build(d) - expected = Vector( - id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) + sparse_values=GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected - def test_build_when_dict_missing_required_fields(self): - with pytest.raises(ValueError, match="Vector dictionary is missing required fields"): - d = {"values": [0.1, 0.2, 0.3]} - VectorFactoryGRPC.build(d) - - def test_build_when_dict_excess_keys(self): - with pytest.raises(ValueError, match="Found excess keys in the vector dictionary"): - d = { - "id": "1", - "values": [0.1, 0.2, 0.3], - "metadata": {"genre": "comedy"}, - "extra": "field", - } - VectorFactoryGRPC.build(d) - @pytest.mark.parametrize( "sv_indices,sv_values", [ @@ -185,11 +221,11 @@ def test_build_when_dict_sparse_values(self, sv_indices, sv_values): "sparse_values": {"indices": sv_indices, "values": sv_values}, } actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}), - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -201,11 +237,11 @@ def test_build_when_dict_sparse_values_when_SparseValues(self): "sparse_values": SparseValues(indices=[0, 2], values=[0.1, 0.3]), } actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}), - sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3]), + sparse_values=GRPCSparseValues(indices=[0, 2], values=[0.1, 0.3]), ) assert actual == expected @@ -242,7 +278,7 @@ def test_build_when_errors_when_other_type(self): @pytest.mark.parametrize("bogus_sparse_values", [1, "not a dict", [1, 2, 3], []]) def test_build_when_invalid_sparse_values_type_in_dict(self, bogus_sparse_values): with pytest.raises( - ValueError, match="Column `sparse_values` is expected to be a dictionary" + ValueError, match="SparseValuesFactory does not know how to handle input type" ): d = { "id": "1", @@ -275,7 +311,243 @@ def test_build_when_sparse_values_is_None(self): "sparse_values": None, } actual = VectorFactoryGRPC.build(d) - expected = Vector( + expected = GRPCVector( id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"}) ) assert actual == expected + + @pytest.mark.parametrize( + "sv", + [ + SparseValues(indices=[0, 4], values=[0.1, 0.3]), + GRPCSparseValues(indices=[0, 4], values=[0.1, 0.3]), + OpenApiSparseValues(indices=[0, 4], values=[0.1, 0.3]), + ], + ) + def test_mixed_types_dict_with_sv_object(self, sv): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": sv, + } + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", + values=[0.1, 0.2, 0.3], + metadata=dict_to_proto_struct({"genre": "comedy"}), + sparse_values=GRPCSparseValues(indices=[0, 4], values=[0.1, 0.3]), + ) + assert actual == expected + + +class TestVectorFactoryGRPC_SparseVectors: + def test_build_when_returns_vector_unmodified(self): + vec = GRPCVector( + id="1", sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]) + ) + assert VectorFactoryGRPC.build(vec) == vec + assert VectorFactoryGRPC.build(vec).__class__ == GRPCVector + + def test_build_returns_grpc_vector(self): + vec = Vector( + id="1", sparse_values=SparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]) + ) + assert VectorFactoryGRPC.build(vec).__class__ == GRPCVector + assert VectorFactoryGRPC.build(vec) == GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({}), + ) + + def test_no_error_when_empty_values_passed(self): + v = Vector(id="1", values=[], sparse_values=SparseValues(indices=[0, 1], values=[0.1, 0.2])) + actual = VectorFactoryGRPC.build(v) + expected = GRPCVector( + id="1", + values=[], + sparse_values=GRPCSparseValues(indices=[0, 1], values=[0.1, 0.2]), + metadata=dict_to_proto_struct({}), + ) + assert actual == expected + + @pytest.mark.parametrize("sv_klass", [SparseValues, GRPCSparseValues]) + def test_when_metadata(self, sv_klass): + v = Vector( + id="1", + values=[], + sparse_values=sv_klass(indices=[0, 1], values=[0.1, 0.2]), + metadata={"genre": "comedy"}, + ) + actual = VectorFactoryGRPC.build(v) + expected = GRPCVector( + id="1", + values=[], + sparse_values=GRPCSparseValues(indices=[0, 1], values=[0.1, 0.2]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + def test_when_dict_with_metadata(self): + v = { + "id": "1", + "values": [], + "sparse_values": {"indices": [0, 1], "values": [0.1, 0.2]}, + "metadata": {"genre": "comedy"}, + } + actual = VectorFactoryGRPC.build(v) + expected = GRPCVector( + id="1", + values=[], + sparse_values=GRPCSparseValues(indices=[0, 1], values=[0.1, 0.2]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + def test_build_when_dict(self): + vec = {"id": "1", "sparse_values": {"indices": [0, 45, 11], "values": [0.1, 0.2, 0.3]}} + actual = VectorFactoryGRPC.build(vec) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({}), + ) + assert actual == expected + + def test_build_when_dict_with_metadata3(self): + vec = { + "id": "1", + "sparse_values": {"indices": [0, 45, 11], "values": [0.1, 0.2, 0.3]}, + "metadata": {"genre": "comedy"}, + } + actual = VectorFactoryGRPC.build(vec) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + def test_build_when_mixed_types(self): + vec = Vector(id="1", sparse_values={"indices": [0, 45, 11], "values": [0.1, 0.2, 0.3]}) + actual = VectorFactoryGRPC.build(vec) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({}), + ) + assert actual == expected + + def test_build_when_nongrpc_vector_it_converts(self): + vec = Vector( + id="1", sparse_values=SparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]) + ) + assert VectorFactoryGRPC.build(vec) == GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({}), + ) + + def test_build_when_nongrpc_vector_with_metadata_it_converts(self): + vec = Vector( + id="1", + sparse_values=SparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata={"genre": "comedy"}, + ) + assert VectorFactoryGRPC.build(vec) == GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[0, 45, 11], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + + def test_build_with_dict_no_metadata(self): + d = {"id": "1", "sparse_values": {"indices": [23, 13, 45], "values": [0.1, 0.2, 0.3]}} + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[23, 13, 45], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({}), + ) + assert actual == expected + + @pytest.mark.parametrize( + "metadata", [{"genre": "comedy"}, dict_to_proto_struct({"genre": "comedy"})] + ) + def test_build_when_dict_with_metadata(self, metadata): + d = { + "id": "1", + "sparse_values": {"indices": [23, 13, 45], "values": [0.1, 0.2, 0.3]}, + "metadata": metadata, + } + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(indices=[23, 13, 45], values=[0.1, 0.2, 0.3]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + @pytest.mark.parametrize("sv_values", [pd.array([0.1, 0.2, 0.3]), np.array([0.1, 0.2, 0.3])]) + def test_build_when_dict_with_special_values(self, sv_values): + d = { + "id": "1", + "sparse_values": {"indices": [10, 12, 14], "values": sv_values}, + "metadata": {"genre": "comedy"}, + } + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(values=[0.1, 0.2, 0.3], indices=[10, 12, 14]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + @pytest.mark.parametrize("sv_indices", [pd.array([1, 2, 3]), np.array([1, 2, 3])]) + def test_build_when_dict_with_special_indices(self, sv_indices): + d = { + "id": "1", + "sparse_values": {"indices": sv_indices, "values": [0.1, 0.2, 0.3]}, + "metadata": {"genre": "comedy"}, + } + actual = VectorFactoryGRPC.build(d) + expected = GRPCVector( + id="1", + sparse_values=GRPCSparseValues(values=[0.1, 0.2, 0.3], indices=[1, 2, 3]), + metadata=dict_to_proto_struct({"genre": "comedy"}), + ) + assert actual == expected + + def test_build_when_dict_missing_required_fields(self): + with pytest.raises(ValueError) as e: + d = {"sparse_values": {"values": [0.1, 0.2, 0.3], "indices": [1, 2, 3]}} + VectorFactoryGRPC.build(d) + + assert "Vector dictionary is missing required fields" in str(e) + assert "id" in str(e) + + def test_spare_values_missing_indices(self): + with pytest.raises(ValueError) as e: + d = {"id": "1", "sparse_values": {"values": [0.1, 0.2, 0.3]}} + VectorFactoryGRPC.build(d) + + assert "Missing required keys" in str(e) + assert "indices" in str(e) + + def test_build_when_dict_excess_keys(self): + with pytest.raises(ValueError, match="Found excess keys in the vector dictionary"): + d = { + "id": "1", + "sparse_values": {"values": [0.1, 0.2, 0.3], "indices": [1, 2, 3]}, + "metadata": {"genre": "comedy"}, + "extra": "field", + } + VectorFactoryGRPC.build(d) + + +class TestVectorFactoryGRPC_EdgeCases: + def test_must_have_values_or_sparse_values(self): + with pytest.raises( + ValueError, + match="At least one of 'values' or 'sparse_values' must be provided in the vector dictionary.", + ): + VectorFactoryGRPC.build({"id": "1"}) From 03d2aa25d3dc1a772298b00146d4da2b151f259d Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 13 Dec 2024 14:32:15 -0500 Subject: [PATCH 04/21] Add codegen script to generate updated stubs from proto file --- codegen/apis | 2 +- codegen/buf.gen.yaml | 8 +++++++ codegen/buf.lock | 6 +++++ codegen/buf.yaml | 12 ++++++++++ codegen/build-grpc.sh | 54 +++++++++++++++++++++++++++++++++++++++++++ poetry.lock | 24 +++++++++---------- 6 files changed, 93 insertions(+), 13 deletions(-) create mode 100644 codegen/buf.gen.yaml create mode 100644 codegen/buf.lock create mode 100644 codegen/buf.yaml create mode 100755 codegen/build-grpc.sh diff --git a/codegen/apis b/codegen/apis index 09510b5d4..8562caf6f 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 09510b5d4074ea00ccdf9dffcc13e05c14c91344 +Subproject commit 8562caf6fdf32f73557416dd0936423b37a2c380 diff --git a/codegen/buf.gen.yaml b/codegen/buf.gen.yaml new file mode 100644 index 000000000..a20bb1604 --- /dev/null +++ b/codegen/buf.gen.yaml @@ -0,0 +1,8 @@ +version: v1 +plugins: + - plugin: buf.build/grpc/python:v1.59.0 + out: gen + - plugin: buf.build/protocolbuffers/python:v29.0 + out: gen + - plugin: buf.build/protocolbuffers/pyi:v29.1 + out: gen diff --git a/codegen/buf.lock b/codegen/buf.lock new file mode 100644 index 000000000..c3c7a03d4 --- /dev/null +++ b/codegen/buf.lock @@ -0,0 +1,6 @@ +# Generated by buf. DO NOT EDIT. +version: v2 +deps: + - name: buf.build/googleapis/googleapis + commit: acd896313c55464b993332136ded1b6e + digest: b5:025d83e25193feb8dac5e5576113c8737006218b3b09fbc0d0ff652614da5424b336edb15bea139eb90d14eba656774a979d1fbdae81cbab2013932b84b98f53 diff --git a/codegen/buf.yaml b/codegen/buf.yaml new file mode 100644 index 000000000..a979e0a5b --- /dev/null +++ b/codegen/buf.yaml @@ -0,0 +1,12 @@ +# For details on buf.yaml configuration, visit https://buf.build/docs/configuration/v2/buf-yaml +version: v2 +lint: + use: + - STANDARD +breaking: + use: + - FILE +deps: + - buf.build/googleapis/googleapis +modules: + - path: apis/_build/2025-01 diff --git a/codegen/build-grpc.sh b/codegen/build-grpc.sh new file mode 100755 index 000000000..f19dc362f --- /dev/null +++ b/codegen/build-grpc.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +set -eux -o pipefail +version=$1 # e.g. 2024-07 + +update_apis_repo() { + echo "Updating apis repo" + pushd codegen/apis + git fetch + git checkout main + git pull + just build + popd +} + +update_buf_config() { + pushd codegen + # Update buf config to find correct proto version + sed -i '' "s/[0-9][0-9][0-9][0-9]-[0-1][0-9]/${version}/g" buf.yaml + + # Clean before building + rm -rf gen + + # Ensure path valid by running the buf build command + buf build + popd +} + +buf_generate() { + pushd codegen + # Generate the python code + buf generate + popd +} + +update_apis_repo +update_buf_config +buf_generate + +dest="pinecone/core/grpc/protos/" + +# Remove existing files in dest +rm -rf "${dest}*.py" +rm -rf "${dest}*.pyi" + +find codegen/gen/ -name "*.py" | while IFS= read -r file; do + sed -i '' "s/^import db_data/import pinecone.core.grpc.protos.db_data/g" "${file}" +done + +# Copy the new generated files to dest directory +cp codegen/gen/* ${dest} + +# Cleanup the intermediate files that were generated +rm -rf codegen/gen diff --git a/poetry.lock b/poetry.lock index 348b32da7..c4b2b6e10 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1038,22 +1038,22 @@ virtualenv = ">=20.10.0" [[package]] name = "protobuf" -version = "5.28.3" +version = "5.29.1" description = "" optional = false python-versions = ">=3.8" files = [ - {file = "protobuf-5.28.3-cp310-abi3-win32.whl", hash = "sha256:0c4eec6f987338617072592b97943fdbe30d019c56126493111cf24344c1cc24"}, - {file = "protobuf-5.28.3-cp310-abi3-win_amd64.whl", hash = "sha256:91fba8f445723fcf400fdbe9ca796b19d3b1242cd873907979b9ed71e4afe868"}, - {file = "protobuf-5.28.3-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:a3f6857551e53ce35e60b403b8a27b0295f7d6eb63d10484f12bc6879c715687"}, - {file = "protobuf-5.28.3-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:3fa2de6b8b29d12c61911505d893afe7320ce7ccba4df913e2971461fa36d584"}, - {file = "protobuf-5.28.3-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:712319fbdddb46f21abb66cd33cb9e491a5763b2febd8f228251add221981135"}, - {file = "protobuf-5.28.3-cp38-cp38-win32.whl", hash = "sha256:3e6101d095dfd119513cde7259aa703d16c6bbdfae2554dfe5cfdbe94e32d548"}, - {file = "protobuf-5.28.3-cp38-cp38-win_amd64.whl", hash = "sha256:27b246b3723692bf1068d5734ddaf2fccc2cdd6e0c9b47fe099244d80200593b"}, - {file = "protobuf-5.28.3-cp39-cp39-win32.whl", hash = "sha256:135658402f71bbd49500322c0f736145731b16fc79dc8f367ab544a17eab4535"}, - {file = "protobuf-5.28.3-cp39-cp39-win_amd64.whl", hash = "sha256:70585a70fc2dd4818c51287ceef5bdba6387f88a578c86d47bb34669b5552c36"}, - {file = "protobuf-5.28.3-py3-none-any.whl", hash = "sha256:cee1757663fa32a1ee673434fcf3bf24dd54763c79690201208bafec62f19eed"}, - {file = "protobuf-5.28.3.tar.gz", hash = "sha256:64badbc49180a5e401f373f9ce7ab1d18b63f7dd4a9cdc43c92b9f0b481cef7b"}, + {file = "protobuf-5.29.1-cp310-abi3-win32.whl", hash = "sha256:22c1f539024241ee545cbcb00ee160ad1877975690b16656ff87dde107b5f110"}, + {file = "protobuf-5.29.1-cp310-abi3-win_amd64.whl", hash = "sha256:1fc55267f086dd4050d18ef839d7bd69300d0d08c2a53ca7df3920cc271a3c34"}, + {file = "protobuf-5.29.1-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:d473655e29c0c4bbf8b69e9a8fb54645bc289dead6d753b952e7aa660254ae18"}, + {file = "protobuf-5.29.1-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:b5ba1d0e4c8a40ae0496d0e2ecfdbb82e1776928a205106d14ad6985a09ec155"}, + {file = "protobuf-5.29.1-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:8ee1461b3af56145aca2800e6a3e2f928108c749ba8feccc6f5dd0062c410c0d"}, + {file = "protobuf-5.29.1-cp38-cp38-win32.whl", hash = "sha256:50879eb0eb1246e3a5eabbbe566b44b10348939b7cc1b267567e8c3d07213853"}, + {file = "protobuf-5.29.1-cp38-cp38-win_amd64.whl", hash = "sha256:027fbcc48cea65a6b17028510fdd054147057fa78f4772eb547b9274e5219331"}, + {file = "protobuf-5.29.1-cp39-cp39-win32.whl", hash = "sha256:5a41deccfa5e745cef5c65a560c76ec0ed8e70908a67cc8f4da5fce588b50d57"}, + {file = "protobuf-5.29.1-cp39-cp39-win_amd64.whl", hash = "sha256:012ce28d862ff417fd629285aca5d9772807f15ceb1a0dbd15b88f58c776c98c"}, + {file = "protobuf-5.29.1-py3-none-any.whl", hash = "sha256:32600ddb9c2a53dedc25b8581ea0f1fd8ea04956373c0c07577ce58d312522e0"}, + {file = "protobuf-5.29.1.tar.gz", hash = "sha256:683be02ca21a6ffe80db6dd02c0b5b2892322c59ca57fd6c872d652cb80549cb"}, ] [[package]] From 6db3421ef609db31005d780698d8c48374c2caed Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 13 Dec 2024 15:08:12 -0500 Subject: [PATCH 05/21] Disable tests on dev release build --- .github/workflows/alpha-release.yaml | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/.github/workflows/alpha-release.yaml b/.github/workflows/alpha-release.yaml index 814976304..fe27a4fdb 100644 --- a/.github/workflows/alpha-release.yaml +++ b/.github/workflows/alpha-release.yaml @@ -24,22 +24,22 @@ on: default: 'rc1' jobs: - unit-tests: - uses: './.github/workflows/testing-unit.yaml' - secrets: inherit - integration-tests: - uses: './.github/workflows/testing-integration.yaml' - secrets: inherit - dependency-tests: - uses: './.github/workflows/testing-dependency.yaml' - secrets: inherit + # unit-tests: + # uses: './.github/workflows/testing-unit.yaml' + # secrets: inherit + # integration-tests: + # uses: './.github/workflows/testing-integration.yaml' + # secrets: inherit + # dependency-tests: + # uses: './.github/workflows/testing-dependency.yaml' + # secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' - needs: - - unit-tests - - integration-tests - - dependency-tests + # needs: + # - unit-tests + # - integration-tests + # - dependency-tests with: isPrerelease: true ref: ${{ inputs.ref }} @@ -49,4 +49,3 @@ jobs: secrets: PYPI_USERNAME: __token__ PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PUBLISH_TOKEN }} - From f5d386cb5dca86a5e391b181b85d7d22a52b4234 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 13 Dec 2024 15:46:05 -0500 Subject: [PATCH 06/21] Adjust fetch return type --- pinecone/data/dataclasses/__init__.py | 1 + pinecone/data/dataclasses/fetch_response.py | 11 +++++++++++ pinecone/data/index.py | 9 +++++++-- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 pinecone/data/dataclasses/fetch_response.py diff --git a/pinecone/data/dataclasses/__init__.py b/pinecone/data/dataclasses/__init__.py index fddb08b19..c481d1ab4 100644 --- a/pinecone/data/dataclasses/__init__.py +++ b/pinecone/data/dataclasses/__init__.py @@ -1,2 +1,3 @@ from .sparse_values import SparseValues from .vector import Vector +from .fetch_response import FetchResponse diff --git a/pinecone/data/dataclasses/fetch_response.py b/pinecone/data/dataclasses/fetch_response.py new file mode 100644 index 000000000..e8d280695 --- /dev/null +++ b/pinecone/data/dataclasses/fetch_response.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +from typing import Dict + +from .vector import Vector + + +@dataclass +class FetchResponse: + namespace: str + vectors: Dict[str, Vector] + usage: Dict[str, int] diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 88a0d5465..9eed8b43a 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -16,7 +16,7 @@ UpsertResponse, ListResponse, ) -from .dataclasses import Vector, SparseValues +from .dataclasses import Vector, SparseValues, FetchResponse from .interfaces import IndexInterface from .request_factory import IndexRequestFactory from .features.bulk_import import ImportFeatureMixin @@ -209,7 +209,12 @@ def delete( @validate_and_convert_errors def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: args_dict = parse_non_empty_args([("namespace", namespace)]) - return self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) + result = self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) + return FetchResponse( + namespace=namespace, + vectors={k: Vector.from_dict(v) for k, v in result.vectors}, + usage=result.usage, + ) @validate_and_convert_errors def query( From 41ddc88a86ae2eceef803e091a864a565bfab1ae Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 16 Dec 2024 13:44:07 -0500 Subject: [PATCH 07/21] mypy type fixes --- pinecone/control/pinecone_interface.py | 4 +- pinecone/data/dataclasses/sparse_values.py | 7 +- pinecone/data/dataclasses/vector.py | 19 +- pinecone/data/index.py | 28 ++- pinecone/data/interfaces.py | 15 +- pinecone/data/request_factory.py | 20 +-- pinecone/data/sparse_values_factory.py | 6 +- pinecone/data/types/__init__.py | 4 + .../data/types/sparse_vector_typed_dict.py | 6 + pinecone/data/types/vector_metadata_dict.py | 4 + pinecone/data/types/vector_tuple.py | 3 + pinecone/data/types/vector_typed_dict.py | 9 + pinecone/grpc/index_grpc.py | 8 +- tests/integration/data/test_list_sparse.py | 170 ++++++++++++++++++ 14 files changed, 244 insertions(+), 59 deletions(-) create mode 100644 pinecone/data/types/__init__.py create mode 100644 pinecone/data/types/sparse_vector_typed_dict.py create mode 100644 pinecone/data/types/vector_metadata_dict.py create mode 100644 pinecone/data/types/vector_tuple.py create mode 100644 pinecone/data/types/vector_typed_dict.py create mode 100644 tests/integration/data/test_list_sparse.py diff --git a/pinecone/control/pinecone_interface.py b/pinecone/control/pinecone_interface.py index 1a6381bdd..439644ae0 100644 --- a/pinecone/control/pinecone_interface.py +++ b/pinecone/control/pinecone_interface.py @@ -177,10 +177,10 @@ def create_index( name: str, spec: Union[Dict, ServerlessSpec, PodSpec], dimension: Optional[int], - metric: Optional[str] = "cosine", + metric: Optional[Literal["cosine", "euclidean", "dotproduct"]] = "cosine", timeout: Optional[int] = None, deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", - vector_type: Optional[str] = "dense", + vector_type: Optional[Literal["dense", "sparse"]] = "dense", ): """Creates a Pinecone index. diff --git a/pinecone/data/dataclasses/sparse_values.py b/pinecone/data/dataclasses/sparse_values.py index c5a34a29b..536d365e5 100644 --- a/pinecone/data/dataclasses/sparse_values.py +++ b/pinecone/data/dataclasses/sparse_values.py @@ -1,7 +1,8 @@ from dataclasses import dataclass -from typing import Any, Dict, List +from typing import List from .utils import DictLike +from ..types import SparseVectorTypedDict @dataclass @@ -9,11 +10,11 @@ class SparseValues(DictLike): indices: List[int] values: List[float] - def to_dict(self) -> Dict[str, Any]: + def to_dict(self) -> SparseVectorTypedDict: return {"indices": self.indices, "values": self.values} @staticmethod - def from_dict(sparse_values_dict: Dict[str, Any]) -> "SparseValues": + def from_dict(sparse_values_dict: SparseVectorTypedDict) -> "SparseValues": return SparseValues( indices=sparse_values_dict["indices"], values=sparse_values_dict["values"] ) diff --git a/pinecone/data/dataclasses/vector.py b/pinecone/data/dataclasses/vector.py index 56c21a835..ef280189b 100644 --- a/pinecone/data/dataclasses/vector.py +++ b/pinecone/data/dataclasses/vector.py @@ -1,6 +1,7 @@ -from typing import Any, Dict, List, Optional, Union +from typing import List, Optional from .sparse_values import SparseValues from .utils import DictLike +from ..types import VectorTypedDict, VectorMetadataTypedDict from dataclasses import dataclass, field @@ -9,15 +10,15 @@ class Vector(DictLike): id: str values: List[float] = field(default_factory=list) - metadata: Optional[Dict[str, Union[str, List[str]]]] = None + metadata: Optional[VectorMetadataTypedDict] = None sparse_values: Optional[SparseValues] = None def __post_init__(self): if self.sparse_values is None and len(self.values) == 0: raise ValueError("The values and sparse_values fields cannot both be empty") - def to_dict(self) -> Dict[str, Any]: - vector_dict = {"id": self.id, "values": self.values} + def to_dict(self) -> VectorTypedDict: + vector_dict: VectorTypedDict = {"id": self.id, "values": self.values} if self.metadata is not None: vector_dict["metadata"] = self.metadata if self.sparse_values is not None: @@ -25,10 +26,16 @@ def to_dict(self) -> Dict[str, Any]: return vector_dict @staticmethod - def from_dict(vector_dict: Dict[str, Any]) -> "Vector": + def from_dict(vector_dict: VectorTypedDict) -> "Vector": + passed_sparse_values = vector_dict.get("sparse_values") + if passed_sparse_values is not None: + parsed_sparse_values = SparseValues.from_dict(passed_sparse_values) + else: + parsed_sparse_values = None + return Vector( id=vector_dict["id"], values=vector_dict["values"], metadata=vector_dict.get("metadata"), - sparse_values=SparseValues.from_dict(vector_dict.get("sparse_values")), + sparse_values=parsed_sparse_values, ) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 9eed8b43a..3f302b81e 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -20,6 +20,7 @@ from .interfaces import IndexInterface from .request_factory import IndexRequestFactory from .features.bulk_import import ImportFeatureMixin +from .types import SparseVectorTypedDict, VectorTypedDict, VectorMetadataTypedDict, VectorTuple from ..utils import ( setup_openapi_client, parse_non_empty_args, @@ -113,7 +114,7 @@ def __exit__(self, exc_type, exc_value, traceback): @validate_and_convert_errors def upsert( self, - vectors: Union[List[Vector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], namespace: Optional[str] = None, batch_size: Optional[int] = None, show_progress: bool = True, @@ -148,7 +149,7 @@ def upsert( def _upsert_batch( self, - vectors: Union[List[Vector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], namespace: Optional[str], _check_type: bool, **kwargs, @@ -211,7 +212,7 @@ def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> Fe args_dict = parse_non_empty_args([("namespace", namespace)]) result = self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) return FetchResponse( - namespace=namespace, + namespace=result.namespace, vectors={k: Vector.from_dict(v) for k, v in result.vectors}, usage=result.usage, ) @@ -227,9 +228,7 @@ def query( filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> Union[QueryResponse, ApplyResult]: response = self._query( @@ -260,9 +259,7 @@ def _query( filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> QueryResponse: if len(args) > 0: @@ -286,7 +283,7 @@ def _query( @validate_and_convert_errors def query_namespaces( self, - vector: List[float], + vector: Optional[List[float]], namespaces: List[str], metric: Literal["cosine", "euclidean", "dotproduct"], top_k: Optional[int] = None, @@ -300,7 +297,8 @@ def query_namespaces( ) -> QueryNamespacesResults: if namespaces is None or len(namespaces) == 0: raise ValueError("At least one namespace must be specified") - if len(vector) == 0: + if sparse_vector is None and vector is not None and len(vector) == 0: + # If querying with a vector, it must not be empty raise ValueError("Query vector must not be empty") overall_topk = top_k if top_k is not None else 10 @@ -336,13 +334,9 @@ def update( self, id: str, values: Optional[List[float]] = None, - set_metadata: Optional[ - Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] - ] = None, + set_metadata: Optional[VectorMetadataTypedDict] = None, namespace: Optional[str] = None, - sparse_values: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> Dict[str, Any]: return self._vector_api.update_vector( diff --git a/pinecone/data/interfaces.py b/pinecone/data/interfaces.py index 117155d9f..0e3aad8a3 100644 --- a/pinecone/data/interfaces.py +++ b/pinecone/data/interfaces.py @@ -12,13 +12,14 @@ ) from .query_results_aggregator import QueryNamespacesResults from multiprocessing.pool import ApplyResult +from .types import VectorTypedDict, SparseVectorTypedDict, VectorMetadataTypedDict class IndexInterface(ABC): @abstractmethod def upsert( self, - vectors: Union[List[Vector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[tuple], List[VectorTypedDict]], namespace: Optional[str] = None, batch_size: Optional[int] = None, show_progress: bool = True, @@ -229,9 +230,7 @@ def query_namespaces( filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> QueryNamespacesResults: """The query_namespaces() method is used to make a query to multiple namespaces in parallel and combine the results into one result set. @@ -285,13 +284,9 @@ def update( self, id: str, values: Optional[List[float]] = None, - set_metadata: Optional[ - Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] - ] = None, + set_metadata: Optional[VectorMetadataTypedDict] = None, namespace: Optional[str] = None, - sparse_values: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> Dict[str, Any]: """ diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py index 20dd5a42b..20f0c8c63 100644 --- a/pinecone/data/request_factory.py +++ b/pinecone/data/request_factory.py @@ -4,21 +4,21 @@ from pinecone.core.openapi.db_data.models import ( QueryRequest, UpsertRequest, - Vector, DeleteRequest, UpdateRequest, DescribeIndexStatsRequest, - SparseValues, ) from ..utils import parse_non_empty_args from .vector_factory import VectorFactory from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS +from .types import VectorTypedDict, SparseVectorTypedDict, VectorMetadataTypedDict, VectorTuple +from .dataclasses import Vector, SparseValues logger = logging.getLogger(__name__) def parse_sparse_values_arg( - sparse_values: Optional[Union[SparseValues, Dict[str, Union[List[float], List[int]]]]], + sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]], ) -> Optional[SparseValues]: if sparse_values is None: return None @@ -53,9 +53,7 @@ def query_request( filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> QueryRequest: if vector is not None and id is not None: @@ -82,7 +80,7 @@ def query_request( @staticmethod def upsert_request( - vectors: Union[List[Vector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], namespace: Optional[str], _check_type: bool, **kwargs, @@ -117,13 +115,9 @@ def delete_request( def update_request( id: str, values: Optional[List[float]] = None, - set_metadata: Optional[ - Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] - ] = None, + set_metadata: Optional[VectorMetadataTypedDict] = None, namespace: Optional[str] = None, - sparse_values: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, + sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> UpdateRequest: _check_type = kwargs.pop("_check_type", False) diff --git a/pinecone/data/sparse_values_factory.py b/pinecone/data/sparse_values_factory.py index 4f3d2588c..dc043b976 100644 --- a/pinecone/data/sparse_values_factory.py +++ b/pinecone/data/sparse_values_factory.py @@ -1,5 +1,5 @@ from collections.abc import Mapping -from typing import Union, Dict +from typing import Union, Dict, Optional from ..utils import convert_to_list @@ -17,7 +17,9 @@ class SparseValuesFactory: """SparseValuesFactory is used to convert various types of user input into SparseValues objects used in generated request code.""" @staticmethod - def build(input: Union[Dict, SparseValues]) -> OpenApiSparseValues: + def build( + input: Union[Dict, Optional[SparseValues], OpenApiSparseValues], + ) -> Optional[OpenApiSparseValues]: if input is None: return input if isinstance(input, OpenApiSparseValues): diff --git a/pinecone/data/types/__init__.py b/pinecone/data/types/__init__.py new file mode 100644 index 000000000..34dbe662c --- /dev/null +++ b/pinecone/data/types/__init__.py @@ -0,0 +1,4 @@ +from .sparse_vector_typed_dict import SparseVectorTypedDict +from .vector_typed_dict import VectorTypedDict +from .vector_metadata_dict import VectorMetadataTypedDict +from .vector_tuple import VectorTuple diff --git a/pinecone/data/types/sparse_vector_typed_dict.py b/pinecone/data/types/sparse_vector_typed_dict.py new file mode 100644 index 000000000..03faf9beb --- /dev/null +++ b/pinecone/data/types/sparse_vector_typed_dict.py @@ -0,0 +1,6 @@ +from typing import TypedDict, List + + +class SparseVectorTypedDict(TypedDict): + indices: List[int] + values: List[float] diff --git a/pinecone/data/types/vector_metadata_dict.py b/pinecone/data/types/vector_metadata_dict.py new file mode 100644 index 000000000..3eae355b7 --- /dev/null +++ b/pinecone/data/types/vector_metadata_dict.py @@ -0,0 +1,4 @@ +from typing import Dict, List, Union + +VectorDictMetadataValue = Union[str, int, float, List[str], List[int], List[float]] +VectorMetadataTypedDict = Dict[str, VectorDictMetadataValue] diff --git a/pinecone/data/types/vector_tuple.py b/pinecone/data/types/vector_tuple.py new file mode 100644 index 000000000..302345b52 --- /dev/null +++ b/pinecone/data/types/vector_tuple.py @@ -0,0 +1,3 @@ +from typing import Tuple, List + +VectorTuple = Tuple[str, List[float]] diff --git a/pinecone/data/types/vector_typed_dict.py b/pinecone/data/types/vector_typed_dict.py new file mode 100644 index 000000000..20c1e6e7d --- /dev/null +++ b/pinecone/data/types/vector_typed_dict.py @@ -0,0 +1,9 @@ +from .sparse_vector_typed_dict import SparseVectorTypedDict +from typing import TypedDict, List + + +class VectorTypedDict(TypedDict, total=False): + values: List[float] + metadata: dict + sparse_values: SparseVectorTypedDict + id: str diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index fd6e1edc8..7d4763e0d 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -1,5 +1,5 @@ import logging -from typing import Optional, Dict, Union, List, Tuple, Any, TypedDict, Iterable, cast, Literal +from typing import Optional, Dict, Union, List, Tuple, Any, Iterable, cast, Literal from google.protobuf import json_format @@ -42,6 +42,7 @@ from pinecone.core.grpc.protos.db_data_2025_01_pb2_grpc import VectorServiceStub from .base import GRPCIndexBase from .future import PineconeGrpcFuture +from ..data.types import SparseVectorTypedDict __all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] @@ -49,11 +50,6 @@ _logger = logging.getLogger(__name__) -class SparseVectorTypedDict(TypedDict): - indices: List[int] - values: List[float] - - class GRPCIndex(GRPCIndexBase): """A client for interacting with a Pinecone index via GRPC API.""" diff --git a/tests/integration/data/test_list_sparse.py b/tests/integration/data/test_list_sparse.py new file mode 100644 index 000000000..c24635258 --- /dev/null +++ b/tests/integration/data/test_list_sparse.py @@ -0,0 +1,170 @@ +import pytest +from pinecone import Vector, SparseValues +from ..helpers import poll_stats_for_namespace + + +@pytest.fixture(scope="class") +def seed_sparse_index(sparse_idx): + sparse_idx.upsert( + vectors=[ + Vector( + id=str(i), + sparse_values=SparseValues( + indices=[i, i * 2, i * 3], values=[i * 0.1, i * 0.2, i * 0.3] + ), + ) + for i in range(1000) + ], + batch_size=100, + namespace="", + ) + + sparse_idx.upsert( + vectors=[ + Vector( + id=str(i), + sparse_values=SparseValues( + indices=[i, i * 2, i * 3], values=[i * 0.1, i * 0.2, i * 0.3] + ), + ) + for i in range(1000) + ], + batch_size=100, + namespace="nondefault", + ) + + print("seeding sparse index") + poll_stats_for_namespace(sparse_idx, "", 1000, max_sleep=120) + poll_stats_for_namespace(sparse_idx, "nondefault", 1000, max_sleep=120) + + yield + + +@pytest.mark.usefixtures("seed_sparse_index") +class TestListPaginated_SparseIndex: + def test_list_when_no_results(self, sparse_idx): + results = sparse_idx.list_paginated(namespace="no-results") + assert results is not None + assert results.namespace == "no-results" + assert len(results.vectors) == 0 + # assert results.pagination == None + + def test_list_no_args(self, sparse_idx): + results = sparse_idx.list_paginated() + + assert results is not None + assert len(results.vectors) == 9 + assert results.namespace == "" + # assert results.pagination == None + + def test_list_when_limit(self, sparse_idx, list_namespace): + results = sparse_idx.list_paginated(limit=10, namespace=list_namespace) + + assert results is not None + assert len(results.vectors) == 10 + assert results.namespace == list_namespace + assert results.pagination is not None + assert results.pagination.next is not None + assert isinstance(results.pagination.next, str) + assert results.pagination.next != "" + + def test_list_when_using_pagination(self, sparse_idx, list_namespace): + results = sparse_idx.list_paginated(prefix="99", limit=5, namespace=list_namespace) + next_results = sparse_idx.list_paginated( + prefix="99", limit=5, namespace=list_namespace, pagination_token=results.pagination.next + ) + next_next_results = sparse_idx.list_paginated( + prefix="99", + limit=5, + namespace=list_namespace, + pagination_token=next_results.pagination.next, + ) + + assert results.namespace == list_namespace + assert len(results.vectors) == 5 + assert [v.id for v in results.vectors] == ["99", "990", "991", "992", "993"] + assert len(next_results.vectors) == 5 + assert [v.id for v in next_results.vectors] == ["994", "995", "996", "997", "998"] + assert len(next_next_results.vectors) == 1 + assert [v.id for v in next_next_results.vectors] == ["999"] + # assert next_next_results.pagination == None + + +class TestList: + def test_list_with_defaults(self, sparse_idx): + pages = [] + page_sizes = [] + page_count = 0 + for ids in sparse_idx.list(): + page_count += 1 + assert ids is not None + page_sizes.append(len(ids)) + pages.append(ids) + + assert page_count == 1 + assert page_sizes == [9] + + def test_list(self, sparse_idx, list_namespace): + results = sparse_idx.list(prefix="99", limit=20, namespace=list_namespace) + + page_count = 0 + for ids in results: + page_count += 1 + assert ids is not None + assert len(ids) == 11 + assert ids == [ + "99", + "990", + "991", + "992", + "993", + "994", + "995", + "996", + "997", + "998", + "999", + ] + assert page_count == 1 + + def test_list_when_no_results_for_prefix(self, sparse_idx, list_namespace): + page_count = 0 + for ids in sparse_idx.list(prefix="no-results", namespace=list_namespace): + page_count += 1 + assert page_count == 0 + + def test_list_when_no_results_for_namespace(self, sparse_idx): + page_count = 0 + for ids in sparse_idx.list(prefix="99", namespace="no-results"): + page_count += 1 + assert page_count == 0 + + def test_list_when_multiple_pages(self, sparse_idx, list_namespace): + pages = [] + page_sizes = [] + page_count = 0 + + for ids in sparse_idx.list(prefix="99", limit=5, namespace=list_namespace): + page_count += 1 + assert ids is not None + page_sizes.append(len(ids)) + pages.append(ids) + + assert page_count == 3 + assert page_sizes == [5, 5, 1] + assert pages[0] == ["99", "990", "991", "992", "993"] + assert pages[1] == ["994", "995", "996", "997", "998"] + assert pages[2] == ["999"] + + def test_list_then_fetch(self, sparse_idx, list_namespace): + vectors = [] + + for ids in sparse_idx.list(prefix="99", limit=5, namespace=list_namespace): + result = sparse_idx.fetch(ids=ids, namespace=list_namespace) + vectors.extend([v for _, v in result.vectors.items()]) + + assert len(vectors) == 11 + assert isinstance(vectors[0], Vector) + assert set([v.id for v in vectors]) == set( + ["99", "990", "991", "992", "993", "994", "995", "996", "997", "998", "999"] + ) From cd55949d35e4ea5cf8159c9c8ce11aa6acc9ebfa Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 16 Dec 2024 14:30:19 -0500 Subject: [PATCH 08/21] More mypy fixes --- pinecone/data/index.py | 12 +++++++++--- pinecone/data/interfaces.py | 4 ++-- pinecone/data/request_factory.py | 10 ++++++++-- pinecone/data/types/__init__.py | 1 + pinecone/grpc/index_grpc.py | 24 ++++++++++++++---------- pinecone/grpc/sparse_values_factory.py | 9 +++++++-- pinecone/grpc/vector_factory_grpc.py | 5 +++-- 7 files changed, 44 insertions(+), 21 deletions(-) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 3f302b81e..3a88126ed 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -20,7 +20,13 @@ from .interfaces import IndexInterface from .request_factory import IndexRequestFactory from .features.bulk_import import ImportFeatureMixin -from .types import SparseVectorTypedDict, VectorTypedDict, VectorMetadataTypedDict, VectorTuple +from .types import ( + SparseVectorTypedDict, + VectorTypedDict, + VectorMetadataTypedDict, + VectorTuple, + FilterTypedDict, +) from ..utils import ( setup_openapi_client, parse_non_empty_args, @@ -225,7 +231,7 @@ def query( vector: Optional[List[float]] = None, id: Optional[str] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, @@ -256,7 +262,7 @@ def _query( vector: Optional[List[float]] = None, id: Optional[str] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, diff --git a/pinecone/data/interfaces.py b/pinecone/data/interfaces.py index 0e3aad8a3..d4fdf9ed9 100644 --- a/pinecone/data/interfaces.py +++ b/pinecone/data/interfaces.py @@ -12,7 +12,7 @@ ) from .query_results_aggregator import QueryNamespacesResults from multiprocessing.pool import ApplyResult -from .types import VectorTypedDict, SparseVectorTypedDict, VectorMetadataTypedDict +from .types import VectorTypedDict, SparseVectorTypedDict, VectorMetadataTypedDict, FilterTypedDict class IndexInterface(ABC): @@ -171,7 +171,7 @@ def query( vector: Optional[List[float]] = None, id: Optional[str] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[ diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py index 20f0c8c63..6370991aa 100644 --- a/pinecone/data/request_factory.py +++ b/pinecone/data/request_factory.py @@ -11,7 +11,13 @@ from ..utils import parse_non_empty_args from .vector_factory import VectorFactory from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS -from .types import VectorTypedDict, SparseVectorTypedDict, VectorMetadataTypedDict, VectorTuple +from .types import ( + VectorTypedDict, + SparseVectorTypedDict, + VectorMetadataTypedDict, + VectorTuple, + FilterTypedDict, +) from .dataclasses import Vector, SparseValues logger = logging.getLogger(__name__) @@ -50,7 +56,7 @@ def query_request( vector: Optional[List[float]] = None, id: Optional[str] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, diff --git a/pinecone/data/types/__init__.py b/pinecone/data/types/__init__.py index 34dbe662c..03364ead4 100644 --- a/pinecone/data/types/__init__.py +++ b/pinecone/data/types/__init__.py @@ -2,3 +2,4 @@ from .vector_typed_dict import VectorTypedDict from .vector_metadata_dict import VectorMetadataTypedDict from .vector_tuple import VectorTuple +from .query_filter import FilterTypedDict diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index 7d4763e0d..452b02518 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -42,7 +42,13 @@ from pinecone.core.grpc.protos.db_data_2025_01_pb2_grpc import VectorServiceStub from .base import GRPCIndexBase from .future import PineconeGrpcFuture -from ..data.types import SparseVectorTypedDict +from ..data.types import ( + SparseVectorTypedDict, + VectorTypedDict, + VectorTuple, + FilterTypedDict, + VectorMetadataTypedDict, +) __all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] @@ -59,7 +65,7 @@ def stub_class(self): def upsert( self, - vectors: Union[List[Vector], List[GRPCVector], List[tuple], List[dict]], + vectors: Union[List[Vector], List[GRPCVector], List[VectorTuple], List[VectorTypedDict]], async_req: bool = False, namespace: Optional[str] = None, batch_size: Optional[int] = None, @@ -223,7 +229,7 @@ def delete( ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, async_req: bool = False, **kwargs, ) -> Union[DeleteResponse, PineconeGrpcFuture]: @@ -249,7 +255,7 @@ def delete( Default is False. namespace (str): The namespace to delete vectors from [optional] If not specified, the default namespace is used. - filter (Dict[str, Union[str, float, int, bool, List, dict]]): + filter (FilterTypedDict): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] @@ -322,7 +328,7 @@ def query( id: Optional[str] = None, namespace: Optional[str] = None, top_k: Optional[int] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[ @@ -410,7 +416,7 @@ def query_namespaces( namespaces: List[str], metric: Literal["cosine", "euclidean", "dotproduct"], top_k: Optional[int] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + filter: Optional[FilterTypedDict] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, @@ -453,9 +459,7 @@ def update( id: str, async_req: bool = False, values: Optional[List[float]] = None, - set_metadata: Optional[ - Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] - ] = None, + set_metadata: Optional[VectorMetadataTypedDict] = None, namespace: Optional[str] = None, sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, **kwargs, @@ -603,7 +607,7 @@ def list(self, **kwargs): done = True def describe_index_stats( - self, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs + self, filter: Optional[FilterTypedDict] = None, **kwargs ) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. diff --git a/pinecone/grpc/sparse_values_factory.py b/pinecone/grpc/sparse_values_factory.py index dc4aa28b9..240cd8e1c 100644 --- a/pinecone/grpc/sparse_values_factory.py +++ b/pinecone/grpc/sparse_values_factory.py @@ -1,9 +1,10 @@ from collections.abc import Mapping -from typing import Union, Dict +from typing import Union, Optional from ..utils import convert_to_list from ..data import SparseValuesTypeError, SparseValuesMissingKeysError +from ..data.types import SparseVectorTypedDict from pinecone.core.grpc.protos.db_data_2025_01_pb2 import SparseValues as GRPCSparseValues from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues @@ -12,7 +13,11 @@ class SparseValuesFactory: @staticmethod - def build(input: Union[Dict, GRPCSparseValues, SparseValues]) -> GRPCSparseValues: + def build( + input: Optional[ + Union[SparseVectorTypedDict, SparseValues, GRPCSparseValues, OpenApiSparseValues] + ], + ) -> Optional[GRPCSparseValues]: if input is None: return input if isinstance(input, GRPCSparseValues): diff --git a/pinecone/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py index 694bb71c8..1fe9572b6 100644 --- a/pinecone/grpc/vector_factory_grpc.py +++ b/pinecone/grpc/vector_factory_grpc.py @@ -1,7 +1,7 @@ import numbers from collections.abc import Iterable, Mapping -from typing import Union, Tuple, Dict +from typing import Union from google.protobuf.struct_pb2 import Struct @@ -14,6 +14,7 @@ VectorTupleLengthError, MetadataDictionaryExpectedError, ) +from ..data.types import VectorTuple, VectorTypedDict from .sparse_values_factory import SparseValuesFactory from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( @@ -31,7 +32,7 @@ class VectorFactoryGRPC: """This class is responsible for building GRPCVector objects from various input types.""" @staticmethod - def build(item: Union[Vector, GRPCVector, Vector, Tuple, Dict]) -> GRPCVector: + def build(item: Union[Vector, GRPCVector, Vector, VectorTuple, VectorTypedDict]) -> GRPCVector: if isinstance(item, GRPCVector): return item elif isinstance(item, Vector) or isinstance(item, OpenApiVector): From ebeb5bed5ff2470abb9d642ffe5627f4640570f4 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 16 Dec 2024 14:41:42 -0500 Subject: [PATCH 09/21] More more mypy fixes --- pinecone/data/types/query_filter.py | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 pinecone/data/types/query_filter.py diff --git a/pinecone/data/types/query_filter.py b/pinecone/data/types/query_filter.py new file mode 100644 index 000000000..927382f61 --- /dev/null +++ b/pinecone/data/types/query_filter.py @@ -0,0 +1,33 @@ +from typing import Literal, Dict, List, Union + +FieldValue = Union[str, int, float, bool] + +ExactMatchFilter = Dict[str, FieldValue] + +EqFilter = Dict[Literal["$eq"], FieldValue] +NeFilter = Dict[Literal["$ne"], FieldValue] + +NumericFieldValue = Union[int, float] +GtFilter = Dict[Literal["$gt"], NumericFieldValue] +GteFilter = Dict[Literal["$gte"], NumericFieldValue] +LtFilter = Dict[Literal["$lt"], NumericFieldValue] +LteFilter = Dict[Literal["$lte"], NumericFieldValue] + +InFilter = Dict[Literal["$in"], List[FieldValue]] +NinFilter = Dict[Literal["$nin"], List[FieldValue]] + + +SimpleFilter = Union[ + ExactMatchFilter, + EqFilter, + NeFilter, + GtFilter, + GteFilter, + LtFilter, + LteFilter, + InFilter, + NinFilter, +] +AndFilter = Dict[Literal["$and"], List[SimpleFilter]] + +FilterTypedDict = Union[SimpleFilter, AndFilter] From 9d8e5b851501c1829023e3965b7141b85e7ad9de Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 16 Dec 2024 20:05:47 -0500 Subject: [PATCH 10/21] Fix failing tests --- pinecone/data/index.py | 3 +- tests/integration/data/test_fetch.py | 88 +++++++++++++++++++- tests/integration/data/test_fetch_future.py | 51 ++++++++++++ tests/integration/data/test_upsert_errors.py | 2 +- 4 files changed, 140 insertions(+), 4 deletions(-) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 3a88126ed..05de54658 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -10,7 +10,6 @@ from pinecone.core.openapi.db_data.api.vector_operations_api import VectorOperationsApi from pinecone.core.openapi.db_data import API_VERSION from pinecone.core.openapi.db_data.models import ( - FetchResponse, QueryResponse, IndexDescription as DescribeIndexStatsResponse, UpsertResponse, @@ -219,7 +218,7 @@ def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> Fe result = self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) return FetchResponse( namespace=result.namespace, - vectors={k: Vector.from_dict(v) for k, v in result.vectors}, + vectors={k: Vector.from_dict(v) for k, v in result.vectors.items()}, usage=result.usage, ) diff --git a/tests/integration/data/test_fetch.py b/tests/integration/data/test_fetch.py index c1b26cfc3..9f7f5968b 100644 --- a/tests/integration/data/test_fetch.py +++ b/tests/integration/data/test_fetch.py @@ -1,7 +1,64 @@ +import logging import pytest -from pinecone import PineconeException, FetchResponse +import random +from ..helpers import poll_fetch_for_ids_in_namespace, poll_stats_for_namespace +from .utils import embedding_values +from pinecone import PineconeException, FetchResponse, Vector, SparseValues +logger = logging.getLogger(__name__) + + +def seed(idx, namespace): + # Upsert without metadata + logger.info(f"Seeding vectors without metadata into namespace '{namespace}'") + idx.upsert( + vectors=[ + ("1", embedding_values(2)), + ("2", embedding_values(2)), + ("3", embedding_values(2)), + ], + namespace=namespace, + ) + + # Upsert with metadata + logger.info(f"Seeding vectors with metadata into namespace '{namespace}'") + idx.upsert( + vectors=[ + Vector( + id="4", values=embedding_values(2), metadata={"genre": "action", "runtime": 120} + ), + Vector(id="5", values=embedding_values(2), metadata={"genre": "comedy", "runtime": 90}), + Vector( + id="6", values=embedding_values(2), metadata={"genre": "romance", "runtime": 240} + ), + ], + namespace=namespace, + ) + + # Upsert with dict + idx.upsert( + vectors=[ + {"id": "7", "values": embedding_values(2)}, + {"id": "8", "values": embedding_values(2)}, + {"id": "9", "values": embedding_values(2)}, + ], + namespace=namespace, + ) + + poll_fetch_for_ids_in_namespace( + idx, ids=["1", "2", "3", "4", "5", "6", "7", "8", "9"], namespace=namespace + ) + + +@pytest.fixture(scope="class") +def seed_for_fetch(idx, namespace): + seed(idx, namespace) + seed(idx, "") + yield + + +@pytest.mark.usefixtures("seed_for_fetch") class TestFetch: def setup_method(self): self.expected_dimension = 2 @@ -76,3 +133,32 @@ def test_fetch_unspecified_namespace(self, idx): assert results.vectors["1"].id == "1" assert results.vectors["1"].values is not None assert results.vectors["4"].metadata is not None + + @pytest.mark.skip(reason="Backend implementation not ready") + def test_fetch_sparse_index(self, sparse_idx): + sparse_idx.upsert( + vectors=[ + Vector( + id=str(i), + sparse_values=SparseValues( + indices=[i, random.randint(2000, 4000)], values=embedding_values(2) + ), + metadata={"genre": "action", "runtime": 120}, + ) + for i in range(50) + ], + namespace="", + ) + + poll_stats_for_namespace(sparse_idx, "", 50, max_sleep=120) + + fetch_results = sparse_idx.fetch(ids=[str(i) for i in range(10)]) + assert fetch_results.namespace == "" + assert len(fetch_results.vectors) == 10 + for i in range(10): + assert fetch_results.vectors[str(i)].id == str(i) + assert fetch_results.vectors[str(i)].values is not None + assert len(fetch_results.vectors[str(i)].values) == 2 + assert fetch_results.vectors[str(i)].metadata is not None + assert fetch_results.vectors[str(i)].metadata["genre"] == "action" + assert fetch_results.vectors[str(i)].metadata["runtime"] == 120 diff --git a/tests/integration/data/test_fetch_future.py b/tests/integration/data/test_fetch_future.py index 19b09ac69..c4e0d48c6 100644 --- a/tests/integration/data/test_fetch_future.py +++ b/tests/integration/data/test_fetch_future.py @@ -1,10 +1,61 @@ import os import pytest +from ..helpers import poll_fetch_for_ids_in_namespace +from .utils import embedding_values +from pinecone import Vector +import logging + +logger = logging.getLogger(__name__) if os.environ.get("USE_GRPC") == "true": from pinecone.grpc import PineconeGrpcFuture +@pytest.fixture(scope="class") +def seed_for_fetch(idx, namespace): + # Upsert without metadata + logger.info("Seeding vectors without metadata") + idx.upsert( + vectors=[ + ("1", embedding_values(2)), + ("2", embedding_values(2)), + ("3", embedding_values(2)), + ], + namespace=namespace, + ) + + # Upsert with metadata + logger.info("Seeding vectors with metadata") + idx.upsert( + vectors=[ + Vector( + id="4", values=embedding_values(2), metadata={"genre": "action", "runtime": 120} + ), + Vector(id="5", values=embedding_values(2), metadata={"genre": "comedy", "runtime": 90}), + Vector( + id="6", values=embedding_values(2), metadata={"genre": "romance", "runtime": 240} + ), + ], + namespace=namespace, + ) + + # Upsert with dict + idx.upsert( + vectors=[ + {"id": "7", "values": embedding_values(2)}, + {"id": "8", "values": embedding_values(2)}, + {"id": "9", "values": embedding_values(2)}, + ], + namespace=namespace, + ) + + poll_fetch_for_ids_in_namespace( + idx, ids=["1", "2", "3", "4", "5", "6", "7", "8", "9"], namespace=namespace + ) + yield + + +@pytest.mark.usefixtures("seed_for_fetch") @pytest.mark.skipif( os.getenv("USE_GRPC") != "true", reason="PineconeGrpcFutures only returned from grpc client" ) diff --git a/tests/integration/data/test_upsert_errors.py b/tests/integration/data/test_upsert_errors.py index 54414fbd3..2274469cc 100644 --- a/tests/integration/data/test_upsert_errors.py +++ b/tests/integration/data/test_upsert_errors.py @@ -124,7 +124,7 @@ def test_upsert_fails_when_sparse_values_indices_values_mismatch_dicts(self, idx class TestUpsertFailsWhenValuesMissing: def test_upsert_fails_when_values_missing_objects(self, idx): - with pytest.raises(TypeError): + with pytest.raises(ValueError): idx.upsert(vectors=[Vector(id="1"), Vector(id="2")]) def test_upsert_fails_when_values_missing_tuples(self, idx): From 534df9bb67c7c358b8329d91b4217bf7caa84018 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 16 Dec 2024 20:16:13 -0500 Subject: [PATCH 11/21] Fix unit tests --- tests/unit/test_index.py | 139 ++++++++++++++++++++------------------- 1 file changed, 73 insertions(+), 66 deletions(-) diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index fe45108ca..72ed7422e 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -2,8 +2,8 @@ import pytest from pinecone.data import _Index -import pinecone.core.openapi.db_data.models as oai_models -from pinecone import QueryResponse, UpsertResponse, SparseValues, Vector +import pinecone.core.openapi.db_data.models as oai +from pinecone import QueryResponse, UpsertResponse, Vector class TestRestIndex: @@ -32,10 +32,10 @@ def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): mocker.patch.object(self.index._vector_api, "upsert_vectors", autospec=True) self.index.upsert([("vec1", self.vals1), ("vec2", self.vals2)], namespace="ns") self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata={}), - Vector(id="vec2", values=self.vals2, metadata={}), + oai.Vector(id="vec1", values=self.vals1, metadata={}), + oai.Vector(id="vec2", values=self.vals2, metadata={}), ], namespace="ns", ) @@ -45,10 +45,10 @@ def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): mocker.patch.object(self.index._vector_api, "upsert_vectors", autospec=True) self.index.upsert([("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2)]) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ] ) ) @@ -62,10 +62,10 @@ def test_upsert_dictOfIdVecMD_UpsertVectorsWithMD(self, mocker): ] ) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ] ) ) @@ -76,8 +76,11 @@ def test_upsert_dictOfIdVecMD_UpsertVectorsWithoutMD(self, mocker): [{"id": self.id1, "values": self.vals1}, {"id": self.id2, "values": self.vals2}] ) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( - vectors=[Vector(id="vec1", values=self.vals1), Vector(id="vec2", values=self.vals2)] + oai.UpsertRequest( + vectors=[ + oai.Vector(id="vec1", values=self.vals1), + oai.Vector(id="vec2", values=self.vals2), + ] ) ) @@ -90,10 +93,14 @@ def test_upsert_dictOfIdVecMD_UpsertVectorsWithSparseValues(self, mocker): ] ) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, sparse_values=SparseValues(**self.sv1)), - Vector(id="vec2", values=self.vals2, sparse_values=SparseValues(**self.sv2)), + oai.Vector( + id="vec1", values=self.vals1, sparse_values=oai.SparseValues(**self.sv1) + ), + oai.Vector( + id="vec2", values=self.vals2, sparse_values=oai.SparseValues(**self.sv2) + ), ] ) ) @@ -102,16 +109,16 @@ def test_upsert_vectors_upsertInputVectors(self, mocker): mocker.patch.object(self.index._vector_api, "upsert_vectors", autospec=True) self.index.upsert( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ], namespace="ns", ) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ], namespace="ns", ) @@ -134,16 +141,16 @@ def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): [async_result.get() for async_result in async_results] index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec1", values=self.vals1, metadata=self.md1)], + oai.UpsertRequest( + vectors=[oai.Vector(id="vec1", values=self.vals1, metadata=self.md1)], namespace="ns", ), async_req=True, ) index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec2", values=self.vals2, metadata=self.md2)], + oai.UpsertRequest( + vectors=[oai.Vector(id="vec2", values=self.vals2, metadata=self.md2)], namespace="ns", ), async_req=True, @@ -170,14 +177,16 @@ def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, m ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec1", values=self.vals1, metadata=self.md1)], namespace="ns" + oai.UpsertRequest( + vectors=[oai.Vector(id="vec1", values=self.vals1, metadata=self.md1)], + namespace="ns", ) ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec2", values=self.vals2, metadata=self.md2)], namespace="ns" + oai.UpsertRequest( + vectors=[oai.Vector(id="vec2", values=self.vals2, metadata=self.md2)], + namespace="ns", ) ) @@ -195,27 +204,28 @@ def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, result = self.index.upsert( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), - Vector(id="vec3", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec3", values=self.vals1, metadata=self.md1), ], namespace="ns", batch_size=2, ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ], namespace="ns", ) ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec3", values=self.vals1, metadata=self.md1)], namespace="ns" + oai.UpsertRequest( + vectors=[oai.Vector(id="vec3", values=self.vals1, metadata=self.md1)], + namespace="ns", ) ) @@ -242,11 +252,11 @@ def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mo ) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), - Vector(id="vec3", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec3", values=self.vals1, metadata=self.md1), ], namespace="ns", ) @@ -275,18 +285,19 @@ def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ], namespace="ns", ) ) self.index._vector_api.upsert_vectors.assert_any_call( - oai_models.UpsertRequest( - vectors=[Vector(id="vec3", values=self.vals1, metadata=self.md1)], namespace="ns" + oai.UpsertRequest( + vectors=[oai.Vector(id="vec3", values=self.vals1, metadata=self.md1)], + namespace="ns", ) ) @@ -308,10 +319,10 @@ def test_upsert_dataframe(self, mocker): self.index.upsert_from_dataframe(df) self.index._vector_api.upsert_vectors.assert_called_once_with( - oai_models.UpsertRequest( + oai.UpsertRequest( vectors=[ - Vector(id="vec1", values=self.vals1, metadata=self.md1), - Vector(id="vec2", values=self.vals2, metadata=self.md2), + oai.Vector(id="vec1", values=self.vals1, metadata=self.md1), + oai.Vector(id="vec2", values=self.vals2, metadata=self.md2), ] ) ) @@ -326,7 +337,7 @@ def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): with pytest.raises(ValueError, match="batch_size must be a positive integer"): self.index.upsert( - vectors=[Vector(id="vec1", values=self.vals1, metadata=self.md1)], + vectors=[oai.Vector(id="vec1", values=self.vals1, metadata=self.md1)], namespace="ns", batch_size=-1, ) @@ -349,7 +360,7 @@ def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): response = QueryResponse( results=[], - matches=[oai_models.ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], + matches=[oai.ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], namespace="test", ) mocker.patch.object( @@ -359,10 +370,10 @@ def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): actual = self.index.query(top_k=10, vector=self.vals1) self.index._vector_api.query_vectors.assert_called_once_with( - oai_models.QueryRequest(top_k=10, vector=self.vals1) + oai.QueryRequest(top_k=10, vector=self.vals1) ) expected = QueryResponse( - matches=[oai_models.ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], + matches=[oai.ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], namespace="test", ) assert expected.to_dict() == actual.to_dict() @@ -371,18 +382,14 @@ def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): mocker.patch.object(self.index._vector_api, "query_vectors", autospec=True) self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns") self.index._vector_api.query_vectors.assert_called_once_with( - oai_models.QueryRequest( - top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns" - ) + oai.QueryRequest(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns") ) def test_query_byVecId_queryByVecId(self, mocker): mocker.patch.object(self.index._vector_api, "query_vectors", autospec=True) self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) self.index._vector_api.query_vectors.assert_called_once_with( - oai_models.QueryRequest( - top_k=10, id="vec1", include_metadata=True, include_values=False - ) + oai.QueryRequest(top_k=10, id="vec1", include_metadata=True, include_values=False) ) def test_query_rejects_both_id_and_vector(self): @@ -405,21 +412,21 @@ def test_delete_byIds_deleteByIds(self, mocker): mocker.patch.object(self.index._vector_api, "delete_vectors", autospec=True) self.index.delete(ids=["vec1", "vec2"]) self.index._vector_api.delete_vectors.assert_called_once_with( - oai_models.DeleteRequest(ids=["vec1", "vec2"]) + oai.DeleteRequest(ids=["vec1", "vec2"]) ) def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): mocker.patch.object(self.index._vector_api, "delete_vectors", autospec=True) self.index.delete(delete_all=True, filter=self.filter1, namespace="ns") self.index._vector_api.delete_vectors.assert_called_once_with( - oai_models.DeleteRequest(delete_all=True, filter=self.filter1, namespace="ns") + oai.DeleteRequest(delete_all=True, filter=self.filter1, namespace="ns") ) def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): mocker.patch.object(self.index._vector_api, "delete_vectors", autospec=True) self.index.delete(delete_all=True) self.index._vector_api.delete_vectors.assert_called_once_with( - oai_models.DeleteRequest(delete_all=True) + oai.DeleteRequest(delete_all=True) ) # endregion @@ -446,14 +453,14 @@ def test_update_byIdAnValues_updateByIdAndValues(self, mocker): mocker.patch.object(self.index._vector_api, "update_vector", autospec=True) self.index.update(id="vec1", values=self.vals1, namespace="ns") self.index._vector_api.update_vector.assert_called_once_with( - oai_models.UpdateRequest(id="vec1", values=self.vals1, namespace="ns") + oai.UpdateRequest(id="vec1", values=self.vals1, namespace="ns") ) def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): mocker.patch.object(self.index._vector_api, "update_vector", autospec=True) self.index.update("vec1", values=self.vals1, metadata=self.md1) self.index._vector_api.update_vector.assert_called_once_with( - oai_models.UpdateRequest(id="vec1", values=self.vals1, metadata=self.md1) + oai.UpdateRequest(id="vec1", values=self.vals1, metadata=self.md1) ) # endregion @@ -464,14 +471,14 @@ def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): mocker.patch.object(self.index._vector_api, "describe_index_stats", autospec=True) self.index.describe_index_stats() self.index._vector_api.describe_index_stats.assert_called_once_with( - oai_models.DescribeIndexStatsRequest() + oai.DescribeIndexStatsRequest() ) def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): mocker.patch.object(self.index._vector_api, "describe_index_stats", autospec=True) self.index.describe_index_stats(filter=self.filter1) self.index._vector_api.describe_index_stats.assert_called_once_with( - oai_models.DescribeIndexStatsRequest(filter=self.filter1) + oai.DescribeIndexStatsRequest(filter=self.filter1) ) # endregion From da31fe08574819a91d410a9043884c5f8c179932 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 01:44:01 -0500 Subject: [PATCH 12/21] Fix integration tests --- pinecone/data/index.py | 12 +- pinecone/data/request_factory.py | 5 +- pinecone/data/types/__init__.py | 2 +- pinecone/data/types/vector_tuple.py | 2 + pinecone/data/vector_factory.py | 10 +- tests/integration/data/conftest.py | 85 +++---- tests/integration/data/seed.py | 16 +- tests/integration/data/test_fetch.py | 33 ++- tests/integration/data/test_fetch_future.py | 3 +- tests/integration/data/test_list.py | 42 ++- tests/integration/data/test_list_errors.py | 38 ++- tests/integration/data/test_list_sparse.py | 3 + tests/integration/data/test_query.py | 119 ++++++--- tests/integration/data/test_query_errors.py | 36 ++- .../data/test_query_namespaces_sparse.py | 239 ++++++++++++++++++ tests/integration/data/test_upsert_dense.py | 12 +- tests/integration/data/test_upsert_errors.py | 3 +- tests/integration/data/test_upsert_future.py | 3 +- tests/integration/data/test_upsert_hybrid.py | 3 +- tests/integration/data/test_upsert_sparse.py | 4 +- tests/integration/data/test_weird_ids.py | 19 +- tests/integration/data/utils.py | 5 - tests/integration/helpers/__init__.py | 1 + tests/integration/helpers/helpers.py | 4 + 24 files changed, 543 insertions(+), 156 deletions(-) create mode 100644 tests/integration/data/test_query_namespaces_sparse.py delete mode 100644 tests/integration/data/utils.py diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 05de54658..5aca9cbf0 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -24,6 +24,7 @@ VectorTypedDict, VectorMetadataTypedDict, VectorTuple, + VectorTupleWithMetadata, FilterTypedDict, ) from ..utils import ( @@ -119,7 +120,9 @@ def __exit__(self, exc_type, exc_value, traceback): @validate_and_convert_errors def upsert( self, - vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], + vectors: Union[ + List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] + ], namespace: Optional[str] = None, batch_size: Optional[int] = None, show_progress: bool = True, @@ -154,7 +157,9 @@ def upsert( def _upsert_batch( self, - vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], + vectors: Union[ + List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] + ], namespace: Optional[str], _check_type: bool, **kwargs, @@ -272,6 +277,9 @@ def _query( "The argument order for `query()` has changed; please use keyword arguments instead of positional arguments. Example: index.query(vector=[0.1, 0.2, 0.3], top_k=10, namespace='my_namespace')" ) + if top_k < 1: + raise ValueError("top_k must be a positive integer") + request = IndexRequestFactory.query_request( top_k=top_k, vector=vector, diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py index 6370991aa..de76530e9 100644 --- a/pinecone/data/request_factory.py +++ b/pinecone/data/request_factory.py @@ -16,6 +16,7 @@ SparseVectorTypedDict, VectorMetadataTypedDict, VectorTuple, + VectorTupleWithMetadata, FilterTypedDict, ) from .dataclasses import Vector, SparseValues @@ -86,7 +87,9 @@ def query_request( @staticmethod def upsert_request( - vectors: Union[List[Vector], List[VectorTuple], List[VectorTypedDict]], + vectors: Union[ + List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] + ], namespace: Optional[str], _check_type: bool, **kwargs, diff --git a/pinecone/data/types/__init__.py b/pinecone/data/types/__init__.py index 03364ead4..38f9c0879 100644 --- a/pinecone/data/types/__init__.py +++ b/pinecone/data/types/__init__.py @@ -1,5 +1,5 @@ from .sparse_vector_typed_dict import SparseVectorTypedDict from .vector_typed_dict import VectorTypedDict from .vector_metadata_dict import VectorMetadataTypedDict -from .vector_tuple import VectorTuple +from .vector_tuple import VectorTuple, VectorTupleWithMetadata from .query_filter import FilterTypedDict diff --git a/pinecone/data/types/vector_tuple.py b/pinecone/data/types/vector_tuple.py index 302345b52..e15d7e7cf 100644 --- a/pinecone/data/types/vector_tuple.py +++ b/pinecone/data/types/vector_tuple.py @@ -1,3 +1,5 @@ +from .vector_metadata_dict import VectorMetadataTypedDict from typing import Tuple, List VectorTuple = Tuple[str, List[float]] +VectorTupleWithMetadata = Tuple[str, List[float], VectorMetadataTypedDict] diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index 70f1c4c90..5ef54a0ba 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -1,7 +1,7 @@ import numbers from collections.abc import Iterable, Mapping -from typing import Union, Tuple, Dict +from typing import Union, Tuple from ..utils import fix_tuple_length, convert_to_list, parse_non_empty_args from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS @@ -21,12 +21,16 @@ MetadataDictionaryExpectedError, ) +from .types import VectorTuple, VectorTypedDict + class VectorFactory: """VectorFactory is used to convert various types of input into vector objects used in generated request code.""" @staticmethod - def build(item: Union[OpenApiVector, Tuple, Dict], check_type: bool = True) -> OpenApiVector: + def build( + item: Union[OpenApiVector, VectorTuple, VectorTypedDict], check_type: bool = True + ) -> OpenApiVector: if isinstance(item, OpenApiVector): return item elif isinstance(item, Vector): @@ -48,7 +52,7 @@ def build(item: Union[OpenApiVector, Tuple, Dict], check_type: bool = True) -> O raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") @staticmethod - def _tuple_to_vector(item, check_type: bool) -> OpenApiVector: + def _tuple_to_vector(item: Tuple, check_type: bool) -> OpenApiVector: if len(item) < 2 or len(item) > 3: raise VectorTupleLengthError(item) id, values, metadata = fix_tuple_length(item, 3) diff --git a/tests/integration/data/conftest.py b/tests/integration/data/conftest.py index 00a43747b..473bf809e 100644 --- a/tests/integration/data/conftest.py +++ b/tests/integration/data/conftest.py @@ -1,17 +1,10 @@ import pytest import os -import time import json -from ..helpers import get_environment_var, random_string, generate_index_name -from .seed import setup_data, setup_list_data, setup_weird_ids_data +from ..helpers import get_environment_var, generate_index_name +import logging -# Test matrix needs to consider the following dimensions: -# - pod vs serverless -# - grpc vs rest -# - metric -> vector vs sparse vector -# - namespace: default vs custom -# - environment: free vs paid -# - with metadata vs without metadata +logger = logging.getLogger(__name__) def api_key(): @@ -23,16 +16,16 @@ def use_grpc(): def build_client(): + config = {"api_key": api_key()} + if use_grpc(): from pinecone.grpc import PineconeGRPC - return PineconeGRPC(api_key=api_key()) + return PineconeGRPC(**config) else: from pinecone import Pinecone - return Pinecone( - api_key=api_key(), additional_headers={"sdk-test-suite": "pinecone-python-client"} - ) + return Pinecone(**config) @pytest.fixture(scope="session") @@ -47,7 +40,7 @@ def client(): @pytest.fixture(scope="session") def metric(): - return get_environment_var("METRIC", "cosine") + return "cosine" @pytest.fixture(scope="session") @@ -60,62 +53,62 @@ def spec(): @pytest.fixture(scope="session") def index_name(): - return generate_index_name("dataplane") + return generate_index_name("dense") @pytest.fixture(scope="session") -def namespace(): - return random_string(10) +def sparse_index_name(): + return generate_index_name("sparse") -@pytest.fixture(scope="session") -def list_namespace(): - return random_string(10) +def build_index_client(client, index_name, index_host): + if use_grpc(): + return client.Index(name=index_name, host=index_host) + else: + return client.Index(name=index_name, host=index_host) @pytest.fixture(scope="session") -def weird_ids_namespace(): - return random_string(10) +def idx(client, index_name, index_host): + return build_index_client(client, index_name, index_host) @pytest.fixture(scope="session") -def idx(client, index_name, index_host): - return client.Index(name=index_name, host=index_host) +def sparse_idx(client, sparse_index_name, sparse_index_host): + return build_index_client(client, sparse_index_name, sparse_index_host) @pytest.fixture(scope="session") def index_host(index_name, metric, spec): pc = build_client() - print("Creating index with name: " + index_name) + if index_name not in pc.list_indexes().names(): + logger.info("Creating index with name: " + index_name) pc.create_index(name=index_name, dimension=2, metric=metric, spec=spec) + else: + logger.info("Index with name " + index_name + " already exists") + description = pc.describe_index(name=index_name) yield description.host - print("Deleting index with name: " + index_name) + logger.info("Deleting index with name: " + index_name) pc.delete_index(index_name, -1) -@pytest.fixture(scope="session", autouse=True) -def seed_data(idx, namespace, index_host, list_namespace, weird_ids_namespace): - print("Seeding data in host " + index_host) +@pytest.fixture(scope="session") +def sparse_index_host(sparse_index_name, spec): + pc = build_client() - if os.getenv("SKIP_WEIRD") != "true": - print("Seeding data in weird ids namespace " + weird_ids_namespace) - setup_weird_ids_data(idx, weird_ids_namespace, True) + if sparse_index_name not in pc.list_indexes().names(): + logger.info("Creating sparse index with name: " + sparse_index_name) + pc.create_index( + name=sparse_index_name, metric="dotproduct", spec=spec, vector_type="sparse" + ) else: - print("Skipping seeding data in weird ids namespace") + logger.info("Sparse index with name " + sparse_index_name + " already exists") - print('Seeding list data in namespace "' + list_namespace + '"') - setup_list_data(idx, list_namespace, True) - - print('Seeding data in namespace "' + namespace + '"') - setup_data(idx, namespace, True) - - print('Seeding data in namespace ""') - setup_data(idx, "", True) - - print("Waiting a bit more to ensure freshness") - time.sleep(120) + description = pc.describe_index(name=sparse_index_name) + yield description.host - yield + logger.info("Deleting sparse index with name: " + sparse_index_name) + pc.delete_index(sparse_index_name, -1) diff --git a/tests/integration/data/seed.py b/tests/integration/data/seed.py index 79d2665f8..827aea9ac 100644 --- a/tests/integration/data/seed.py +++ b/tests/integration/data/seed.py @@ -1,6 +1,6 @@ -from ..helpers import poll_fetch_for_ids_in_namespace +from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values from pinecone import Vector -from .utils import embedding_values + import itertools @@ -45,18 +45,6 @@ def setup_data(idx, target_namespace, wait): ) -def setup_list_data(idx, target_namespace, wait): - # Upsert a bunch more stuff for testing list pagination - for i in range(0, 1000, 50): - idx.upsert( - vectors=[(str(i + d), embedding_values(2)) for d in range(50)], - namespace=target_namespace, - ) - - if wait: - poll_fetch_for_ids_in_namespace(idx, ids=["999"], namespace=target_namespace) - - def weird_invalid_ids(): invisible = [ "â €", # U+2800 diff --git a/tests/integration/data/test_fetch.py b/tests/integration/data/test_fetch.py index 9f7f5968b..5523d27ef 100644 --- a/tests/integration/data/test_fetch.py +++ b/tests/integration/data/test_fetch.py @@ -1,14 +1,23 @@ import logging import pytest import random -from ..helpers import poll_fetch_for_ids_in_namespace, poll_stats_for_namespace -from .utils import embedding_values +from ..helpers import ( + poll_fetch_for_ids_in_namespace, + poll_stats_for_namespace, + embedding_values, + random_string, +) from pinecone import PineconeException, FetchResponse, Vector, SparseValues logger = logging.getLogger(__name__) +@pytest.fixture(scope="session") +def fetch_namespace(): + return random_string(10) + + def seed(idx, namespace): # Upsert without metadata logger.info(f"Seeding vectors without metadata into namespace '{namespace}'") @@ -52,8 +61,8 @@ def seed(idx, namespace): @pytest.fixture(scope="class") -def seed_for_fetch(idx, namespace): - seed(idx, namespace) +def seed_for_fetch(idx, fetch_namespace): + seed(idx, fetch_namespace) seed(idx, "") yield @@ -64,8 +73,8 @@ def setup_method(self): self.expected_dimension = 2 @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) - def test_fetch_multiple_by_id(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_fetch_multiple_by_id(self, idx, fetch_namespace, use_nondefault_namespace): + target_namespace = fetch_namespace if use_nondefault_namespace else "" results = idx.fetch(ids=["1", "2", "4"], namespace=target_namespace) assert isinstance(results, FetchResponse) == True @@ -89,8 +98,8 @@ def test_fetch_multiple_by_id(self, idx, namespace, use_nondefault_namespace): assert len(results.vectors["1"].values) == self.expected_dimension @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) - def test_fetch_single_by_id(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_fetch_single_by_id(self, idx, fetch_namespace, use_nondefault_namespace): + target_namespace = fetch_namespace if use_nondefault_namespace else "" results = idx.fetch(ids=["1"], namespace=target_namespace) assert results.namespace == target_namespace @@ -101,8 +110,8 @@ def test_fetch_single_by_id(self, idx, namespace, use_nondefault_namespace): assert len(results.vectors["1"].values) == self.expected_dimension @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) - def test_fetch_nonexistent_id(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_fetch_nonexistent_id(self, idx, fetch_namespace, use_nondefault_namespace): + target_namespace = fetch_namespace if use_nondefault_namespace else "" # Fetch id that is missing results = idx.fetch(ids=["100"], namespace=target_namespace) @@ -118,8 +127,8 @@ def test_fetch_nonexistent_namespace(self, idx): assert len(results.vectors) == 0 @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) - def test_fetch_with_empty_list_of_ids(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_fetch_with_empty_list_of_ids(self, idx, fetch_namespace, use_nondefault_namespace): + target_namespace = fetch_namespace if use_nondefault_namespace else "" # Fetch with empty list of ids with pytest.raises(PineconeException) as e: diff --git a/tests/integration/data/test_fetch_future.py b/tests/integration/data/test_fetch_future.py index c4e0d48c6..4817380c4 100644 --- a/tests/integration/data/test_fetch_future.py +++ b/tests/integration/data/test_fetch_future.py @@ -1,7 +1,6 @@ import os import pytest -from ..helpers import poll_fetch_for_ids_in_namespace -from .utils import embedding_values +from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values from pinecone import Vector import logging diff --git a/tests/integration/data/test_list.py b/tests/integration/data/test_list.py index 47a18a90a..72f16b762 100644 --- a/tests/integration/data/test_list.py +++ b/tests/integration/data/test_list.py @@ -1,6 +1,31 @@ +import logging +import pytest from pinecone import Vector +from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values, random_string +logger = logging.getLogger(__name__) + +@pytest.fixture(scope="session") +def list_namespace(): + return random_string(10) + + +@pytest.fixture(scope="session") +def seed_for_list(idx, list_namespace, wait=True): + logger.debug(f"Upserting into list namespace '{list_namespace}'") + for i in range(0, 1000, 50): + idx.upsert( + vectors=[(str(i + d), embedding_values(2)) for d in range(50)], namespace=list_namespace + ) + + if wait: + poll_fetch_for_ids_in_namespace(idx, ids=["999"], namespace=list_namespace) + + yield + + +@pytest.mark.usefixtures("seed_for_list") class TestListPaginated: def test_list_when_no_results(self, idx): results = idx.list_paginated(namespace="no-results") @@ -13,8 +38,9 @@ def test_list_no_args(self, idx): results = idx.list_paginated() assert results is not None - assert len(results.vectors) == 9 assert results.namespace == "" + assert results.vectors is not None + assert isinstance(results.vectors, list) # assert results.pagination == None def test_list_when_limit(self, idx, list_namespace): @@ -50,20 +76,8 @@ def test_list_when_using_pagination(self, idx, list_namespace): # assert next_next_results.pagination == None +@pytest.mark.usefixtures("seed_for_list") class TestList: - def test_list_with_defaults(self, idx): - pages = [] - page_sizes = [] - page_count = 0 - for ids in idx.list(): - page_count += 1 - assert ids is not None - page_sizes.append(len(ids)) - pages.append(ids) - - assert page_count == 1 - assert page_sizes == [9] - def test_list(self, idx, list_namespace): results = idx.list(prefix="99", limit=20, namespace=list_namespace) diff --git a/tests/integration/data/test_list_errors.py b/tests/integration/data/test_list_errors.py index 03939cf20..1ab3c4965 100644 --- a/tests/integration/data/test_list_errors.py +++ b/tests/integration/data/test_list_errors.py @@ -1,17 +1,45 @@ from pinecone import PineconeException import pytest +from ..helpers import poll_fetch_for_ids_in_namespace, random_string, embedding_values +import logging +logger = logging.getLogger(__name__) + +@pytest.fixture(scope="session") +def list_errors_namespace(): + return random_string(10) + + +@pytest.fixture(scope="session") +def seed_for_list2(idx, list_errors_namespace, wait=True): + logger.debug(f"Upserting into list namespace '{list_errors_namespace}'") + for i in range(0, 1000, 50): + idx.upsert( + vectors=[(str(i + d), embedding_values(2)) for d in range(50)], + namespace=list_errors_namespace, + ) + + if wait: + poll_fetch_for_ids_in_namespace(idx, ids=["999"], namespace=list_errors_namespace) + + yield + + +@pytest.mark.usefixtures("seed_for_list2") class TestListErrors: - def test_list_change_prefix_while_fetching_next_page(self, idx, list_namespace): - results = idx.list_paginated(prefix="99", limit=5, namespace=list_namespace) + def test_list_change_prefix_while_fetching_next_page(self, idx, list_errors_namespace): + results = idx.list_paginated(prefix="99", limit=5, namespace=list_errors_namespace) with pytest.raises(PineconeException) as e: - idx.list_paginated(prefix="98", limit=5, pagination_token=results.pagination.next) + results = idx.list_paginated( + prefix="98", limit=5, pagination_token=results.pagination.next + ) + print(results) assert "prefix" in str(e.value) @pytest.mark.skip(reason="Bug filed") - def test_list_change_namespace_while_fetching_next_page(self, idx, namespace): - results = idx.list_paginated(limit=5, namespace=namespace) + def test_list_change_namespace_while_fetching_next_page(self, idx, list_errors_namespace): + results = idx.list_paginated(limit=5, namespace=list_errors_namespace) with pytest.raises(PineconeException) as e: idx.list_paginated( limit=5, namespace="new-namespace", pagination_token=results.pagination.next diff --git a/tests/integration/data/test_list_sparse.py b/tests/integration/data/test_list_sparse.py index c24635258..0bfc658d9 100644 --- a/tests/integration/data/test_list_sparse.py +++ b/tests/integration/data/test_list_sparse.py @@ -40,6 +40,7 @@ def seed_sparse_index(sparse_idx): yield +@pytest.mark.skip(reason="Sparse indexes are not yet supported") @pytest.mark.usefixtures("seed_sparse_index") class TestListPaginated_SparseIndex: def test_list_when_no_results(self, sparse_idx): @@ -90,6 +91,8 @@ def test_list_when_using_pagination(self, sparse_idx, list_namespace): # assert next_next_results.pagination == None +@pytest.mark.skip(reason="Sparse indexes are not yet supported") +@pytest.mark.usefixtures("seed_sparse_index") class TestList: def test_list_with_defaults(self, sparse_idx): pages = [] diff --git a/tests/integration/data/test_query.py b/tests/integration/data/test_query.py index 7ff75f09c..09f895c22 100644 --- a/tests/integration/data/test_query.py +++ b/tests/integration/data/test_query.py @@ -1,6 +1,9 @@ import pytest -from pinecone import QueryResponse -from .utils import embedding_values +from pinecone import QueryResponse, Vector +from ..helpers import embedding_values, poll_fetch_for_ids_in_namespace, random_string +import logging + +logger = logging.getLogger(__name__) def find_by_id(matches, id): @@ -8,13 +11,68 @@ def find_by_id(matches, id): return with_id[0] if len(with_id) > 0 else None +@pytest.fixture(scope="session") +def query_namespace(): + return random_string(10) + + +def seed(idx, namespace): + # Upsert without metadata + logger.info(f"Seeding vectors without metadata into namespace '{namespace}'") + idx.upsert( + vectors=[ + ("1", embedding_values(2)), + ("2", embedding_values(2)), + ("3", embedding_values(2)), + ], + namespace=namespace, + ) + + # Upsert with metadata + logger.info(f"Seeding vectors with metadata into namespace '{namespace}'") + idx.upsert( + vectors=[ + Vector( + id="4", values=embedding_values(2), metadata={"genre": "action", "runtime": 120} + ), + Vector(id="5", values=embedding_values(2), metadata={"genre": "comedy", "runtime": 90}), + Vector( + id="6", values=embedding_values(2), metadata={"genre": "romance", "runtime": 240} + ), + ], + namespace=namespace, + ) + + # Upsert with dict + idx.upsert( + vectors=[ + {"id": "7", "values": embedding_values(2)}, + {"id": "8", "values": embedding_values(2)}, + {"id": "9", "values": embedding_values(2)}, + ], + namespace=namespace, + ) + + poll_fetch_for_ids_in_namespace( + idx, ids=["1", "2", "3", "4", "5", "6", "7", "8", "9"], namespace=namespace + ) + + +@pytest.fixture(scope="class") +def seed_for_query(idx, query_namespace): + seed(idx, query_namespace) + seed(idx, "") + yield + + +@pytest.mark.usefixtures("seed_for_query") @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) class TestQuery: def setup_method(self): self.expected_dimension = 2 - def test_query_by_id(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query(id="1", namespace=target_namespace, top_k=10) assert isinstance(results, QueryResponse) == True @@ -29,15 +87,15 @@ def test_query_by_id(self, idx, namespace, use_nondefault_namespace): assert record_with_metadata.metadata is None assert record_with_metadata.values == [] - def test_query_by_vector(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_vector(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query(vector=embedding_values(2), namespace=target_namespace, top_k=10) assert isinstance(results, QueryResponse) == True assert results.namespace == target_namespace - def test_query_by_vector_include_values(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_vector_include_values(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query( vector=embedding_values(2), namespace=target_namespace, include_values=True, top_k=10 @@ -48,8 +106,8 @@ def test_query_by_vector_include_values(self, idx, namespace, use_nondefault_nam assert results.matches[0].values is not None assert len(results.matches[0].values) == self.expected_dimension - def test_query_by_vector_include_metadata(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_vector_include_metadata(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query( vector=embedding_values(2), namespace=target_namespace, include_metadata=True, top_k=10 @@ -62,9 +120,9 @@ def test_query_by_vector_include_metadata(self, idx, namespace, use_nondefault_n assert find_by_id(results.matches, "4").metadata["genre"] == "action" def test_query_by_vector_include_values_and_metadata( - self, idx, namespace, use_nondefault_namespace + self, idx, query_namespace, use_nondefault_namespace ): - target_namespace = namespace if use_nondefault_namespace else "" + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query( vector=embedding_values(2), @@ -90,10 +148,11 @@ def test_query_in_empty_namespace(self, idx): assert len(results.matches) == 0 +@pytest.mark.usefixtures("seed_for_query") @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) class TestQueryWithFilter: - def test_query_by_id_with_filter(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" results = idx.query( id="1", namespace=target_namespace, filter={"genre": "action"}, top_k=10 @@ -103,8 +162,8 @@ def test_query_by_id_with_filter(self, idx, namespace, use_nondefault_namespace) assert len(results.matches) == 1 assert results.matches[0].id == "4" - def test_query_by_id_with_filter_gt(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_gt(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -118,8 +177,8 @@ def test_query_by_id_with_filter_gt(self, idx, namespace, use_nondefault_namespa assert find_by_id(results.matches, "4") is not None assert find_by_id(results.matches, "6") is not None - def test_query_by_id_with_filter_gte(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_gte(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -134,8 +193,8 @@ def test_query_by_id_with_filter_gte(self, idx, namespace, use_nondefault_namesp assert find_by_id(results.matches, "5") is not None assert find_by_id(results.matches, "6") is not None - def test_query_by_id_with_filter_lt(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_lt(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -148,8 +207,8 @@ def test_query_by_id_with_filter_lt(self, idx, namespace, use_nondefault_namespa assert len(results.matches) == 1 assert find_by_id(results.matches, "5") is not None - def test_query_by_id_with_filter_lte(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_lte(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -163,8 +222,8 @@ def test_query_by_id_with_filter_lte(self, idx, namespace, use_nondefault_namesp assert find_by_id(results.matches, "4") is not None assert find_by_id(results.matches, "5") is not None - def test_query_by_id_with_filter_in(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_in(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -178,8 +237,8 @@ def test_query_by_id_with_filter_in(self, idx, namespace, use_nondefault_namespa assert find_by_id(results.matches, "6") is not None @pytest.mark.skip(reason="Seems like a bug in the server") - def test_query_by_id_with_filter_nin(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_nin(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -193,8 +252,8 @@ def test_query_by_id_with_filter_nin(self, idx, namespace, use_nondefault_namesp assert find_by_id(results.matches, "4") is not None assert find_by_id(results.matches, "5") is not None - def test_query_by_id_with_filter_eq(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_eq(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), @@ -208,8 +267,8 @@ def test_query_by_id_with_filter_eq(self, idx, namespace, use_nondefault_namespa assert find_by_id(results.matches, "4") is not None @pytest.mark.skip(reason="Seems like a bug in the server") - def test_query_by_id_with_filter_ne(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_by_id_with_filter_ne(self, idx, query_namespace, use_nondefault_namespace): + target_namespace = query_namespace if use_nondefault_namespace else "" # Vector(id='4', values=embedding_values(2), metadata={'genre': 'action', 'runtime': 120 }), # Vector(id='5', values=embedding_values(2), metadata={'genre': 'comedy', 'runtime': 90 }), diff --git a/tests/integration/data/test_query_errors.py b/tests/integration/data/test_query_errors.py index 48a8e5f56..1c38d8453 100644 --- a/tests/integration/data/test_query_errors.py +++ b/tests/integration/data/test_query_errors.py @@ -1,31 +1,51 @@ import pytest from pinecone import PineconeException +from ..helpers import embedding_values +@pytest.fixture(scope="session") +def query_error_namespace(): + return "query-error-namespace" + + +@pytest.fixture(scope="session") +def seed_for_query_error_cases(idx, query_error_namespace): + idx.upsert( + vectors=[ + ("1", embedding_values(2)), + ("2", embedding_values(2)), + ("3", embedding_values(2)), + ], + namespace=query_error_namespace, + ) + yield + + +@pytest.mark.usefixtures("seed_for_query_error_cases") @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) class TestQueryErrorCases: - def test_query_with_invalid_vector(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_with_invalid_vector(self, idx, query_error_namespace, use_nondefault_namespace): + target_namespace = query_error_namespace if use_nondefault_namespace else "" with pytest.raises(PineconeException) as e: idx.query(vector=[1, 2, 3], namespace=target_namespace, top_k=10) assert "vector" in str(e.value).lower() - def test_query_with_invalid_id(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_with_invalid_id(self, idx, query_error_namespace, use_nondefault_namespace): + target_namespace = query_error_namespace if use_nondefault_namespace else "" with pytest.raises(TypeError): idx.query(id=1, namespace=target_namespace, top_k=10) - def test_query_with_invalid_top_k(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_with_invalid_top_k(self, idx, query_error_namespace, use_nondefault_namespace): + target_namespace = query_error_namespace if use_nondefault_namespace else "" with pytest.raises((PineconeException, ValueError)): idx.query(id="1", namespace=target_namespace, top_k=-1) - def test_query_with_missing_top_k(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_query_with_missing_top_k(self, idx, query_error_namespace, use_nondefault_namespace): + target_namespace = query_error_namespace if use_nondefault_namespace else "" with pytest.raises((TypeError, PineconeException)) as e: idx.query(id="1", namespace=target_namespace) diff --git a/tests/integration/data/test_query_namespaces_sparse.py b/tests/integration/data/test_query_namespaces_sparse.py new file mode 100644 index 000000000..607798ea5 --- /dev/null +++ b/tests/integration/data/test_query_namespaces_sparse.py @@ -0,0 +1,239 @@ +import pytest +from ..helpers import random_string, poll_stats_for_namespace +from pinecone.data.query_results_aggregator import QueryResultsAggregatorInvalidTopKError + +from pinecone import Vector, SparseValues + + +@pytest.mark.skip(reason="Sparse indexes are not yet supported") +class TestQueryNamespacesRest_Sparse: + def test_query_namespaces(self, sparse_idx): + ns_prefix = random_string(5) + ns1 = f"{ns_prefix}-ns1" + ns2 = f"{ns_prefix}-ns2" + ns3 = f"{ns_prefix}-ns3" + + sparse_idx.upsert( + vectors=[ + Vector( + id="id1", + sparse_values=SparseValues(indices=[1, 0, 2], values=[0.1, 0.2, 0.3]), + metadata={"genre": "drama", "key": 1}, + ), + Vector( + id="id2", + sparse_values=SparseValues(indices=[1, 2, 3], values=[0.2, 0.3, 0.3]), + metadata={"genre": "drama", "key": 2}, + ), + Vector( + id="id3", + sparse_values=SparseValues(indices=[1, 4, 5], values=[0.4, 0.5, 0.6]), + metadata={"genre": "action", "key": 3}, + ), + Vector( + id="id4", + sparse_values=SparseValues(indices=[1, 6, 7], values=[0.6, 0.7, 0.7]), + metadata={"genre": "action", "key": 4}, + ), + ], + namespace=ns1, + ) + sparse_idx.upsert( + vectors=[ + Vector( + id="id5", + sparse_values=SparseValues(indices=[1, 8, 9], values=[0.21, 0.22, 0.23]), + metadata={"genre": "drama", "key": 1}, + ), + Vector( + id="id6", + sparse_values=SparseValues(indices=[1, 10, 11], values=[0.22, 0.23, 0.24]), + metadata={"genre": "drama", "key": 2}, + ), + Vector( + id="id7", + sparse_values=SparseValues(indices=[1, 12, 13], values=[0.24, 0.25, 0.26]), + metadata={"genre": "action", "key": 3}, + ), + Vector( + id="id8", + sparse_values=SparseValues(indices=[1, 14, 15], values=[0.26, 0.27, 0.27]), + metadata={"genre": "action", "key": 4}, + ), + ], + namespace=ns2, + ) + sparse_idx.upsert( + vectors=[ + Vector( + id="id9", + sparse_values=SparseValues(indices=[1, 16, 17], values=[0.31, 0.32, 0.33]), + metadata={"genre": "drama", "key": 1}, + ), + Vector( + id="id10", + sparse_values=SparseValues(indices=[1, 18, 19], values=[0.32, 0.33, 0.34]), + metadata={"genre": "drama", "key": 2}, + ), + Vector( + id="id11", + sparse_values=SparseValues(indices=[1, 20, 21], values=[0.34, 0.35, 0.35]), + metadata={"genre": "action", "key": 3}, + ), + Vector( + id="id12", + sparse_values=SparseValues(indices=[1, 22, 23], values=[0.36, 0.37, 0.36]), + metadata={"genre": "action", "key": 4}, + ), + ], + namespace=ns3, + ) + + poll_stats_for_namespace(sparse_idx, namespace=ns1, expected_count=4) + poll_stats_for_namespace(sparse_idx, namespace=ns2, expected_count=4) + poll_stats_for_namespace(sparse_idx, namespace=ns3, expected_count=4) + + results = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + metric="dotproduct", + namespaces=[ns1, ns2, ns3], + include_values=True, + include_metadata=True, + filter={"genre": {"$eq": "drama"}}, + top_k=100, + ) + assert len(results.matches) == 6 + assert results.usage.read_units > 0 + for item in results.matches: + assert item.metadata["genre"] == "drama" + assert results.matches[0].id == "id1" + assert results.matches[0].namespace == ns1 + + # Using dot-style accessors + assert results.matches[0].metadata["genre"] == "drama" + assert results.matches[0].metadata["key"] == 1 + + # Using dictionary-style accessors + assert results.matches[0]["metadata"]["genre"] == "drama" + assert results.matches[0]["metadata"]["key"] == 1 + + # Using .get() accessors + assert results.get("matches", [])[0].get("metadata", {}).get("genre") == "drama" + assert results.matches[0].get("metadata", {}) == {"genre": "drama", "key": 1} + assert results.matches[0].get("metadata", {}).get("genre") == "drama" + + assert results.matches[1].id == "id2" + assert results.matches[1].namespace == ns1 + assert results.matches[2].id == "id5" + assert results.matches[2].namespace == ns2 + + # Non-existent namespace shouldn't cause any problem + results2 = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + namespaces=[ns1, ns2, ns3, f"{ns_prefix}-nonexistent"], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={"genre": {"$eq": "action"}}, + top_k=100, + ) + assert len(results2.matches) == 6 + assert results2.usage.read_units > 0 + for item in results2.matches: + assert item.metadata["genre"] == "action" + + # Test with empty filter, top_k greater than number of results + results3 = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + namespaces=[ns1, ns2, ns3], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={}, + top_k=100, + ) + assert len(results3.matches) == 12 + assert results3.usage.read_units > 0 + + # Test when all results are filtered out + results4 = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1000], values=[24.5]), + namespaces=[ns1, ns2, ns3], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={"genre": {"$eq": "comedy"}}, + top_k=100, + ) + assert len(results4.matches) == 0 + assert results4.usage.read_units > 0 + + # Test with top_k less than number of results + results5 = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + namespaces=[ns1, ns2, ns3], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={}, + top_k=2, + ) + assert len(results5.matches) == 2 + + # Test when all namespaces are non-existent (same as all results filtered / empty) + results6 = sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + namespaces=[ + f"{ns_prefix}-nonexistent1", + f"{ns_prefix}-nonexistent2", + f"{ns_prefix}-nonexistent3", + ], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={"genre": {"$eq": "comedy"}}, + top_k=2, + ) + assert len(results6.matches) == 0 + assert results6.usage.read_units > 0 + + def test_invalid_top_k(self, sparse_idx): + with pytest.raises(QueryResultsAggregatorInvalidTopKError) as e: + sparse_idx.query_namespaces( + sparse_vector=SparseValues(indices=[1], values=[24.5]), + namespaces=["ns1", "ns2", "ns3"], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={}, + top_k=1, + ) + assert ( + str(e.value) + == "Invalid top_k value 1. To aggregate results from multiple queries the top_k must be at least 2." + ) + + def test_missing_namespaces(self, sparse_idx): + with pytest.raises(ValueError) as e: + sparse_idx.query_namespaces( + vector=[0.1, 0.2], + namespaces=[], + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={}, + top_k=2, + ) + assert str(e.value) == "At least one namespace must be specified" + + with pytest.raises(ValueError) as e: + sparse_idx.query_namespaces( + vector=[0.1, 0.2], + namespaces=None, + metric="dotproduct", + include_values=True, + include_metadata=True, + filter={}, + top_k=2, + ) + assert str(e.value) == "At least one namespace must be specified" diff --git a/tests/integration/data/test_upsert_dense.py b/tests/integration/data/test_upsert_dense.py index e36eb2963..dd3be6dd2 100644 --- a/tests/integration/data/test_upsert_dense.py +++ b/tests/integration/data/test_upsert_dense.py @@ -1,13 +1,17 @@ import pytest from pinecone import Vector -from ..helpers import poll_stats_for_namespace -from .utils import embedding_values +from ..helpers import poll_stats_for_namespace, embedding_values, random_string + + +@pytest.fixture(scope="session") +def upsert_dense_namespace(): + return random_string(10) class TestUpsertDense: @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) - def test_upsert_to_namespace(self, idx, namespace, use_nondefault_namespace): - target_namespace = namespace if use_nondefault_namespace else "" + def test_upsert_to_namespace(self, idx, upsert_dense_namespace, use_nondefault_namespace): + target_namespace = upsert_dense_namespace if use_nondefault_namespace else "" # Upsert with tuples idx.upsert( diff --git a/tests/integration/data/test_upsert_errors.py b/tests/integration/data/test_upsert_errors.py index 2274469cc..2ca422b73 100644 --- a/tests/integration/data/test_upsert_errors.py +++ b/tests/integration/data/test_upsert_errors.py @@ -1,8 +1,7 @@ import pytest import os from pinecone import Vector, SparseValues -from .utils import embedding_values -from ..helpers import fake_api_key +from ..helpers import fake_api_key, embedding_values from pinecone import PineconeException diff --git a/tests/integration/data/test_upsert_future.py b/tests/integration/data/test_upsert_future.py index 724aea1d2..44b5a7463 100644 --- a/tests/integration/data/test_upsert_future.py +++ b/tests/integration/data/test_upsert_future.py @@ -1,8 +1,7 @@ import pytest import os from pinecone import Vector, PineconeException -from ..helpers import poll_stats_for_namespace -from .utils import embedding_values +from ..helpers import poll_stats_for_namespace, embedding_values class TestUpsertWithAsyncReq: diff --git a/tests/integration/data/test_upsert_hybrid.py b/tests/integration/data/test_upsert_hybrid.py index 4d1b640e1..59d740213 100644 --- a/tests/integration/data/test_upsert_hybrid.py +++ b/tests/integration/data/test_upsert_hybrid.py @@ -1,8 +1,7 @@ import pytest import os from pinecone import Vector, SparseValues -from ..helpers import poll_stats_for_namespace -from .utils import embedding_values +from ..helpers import poll_stats_for_namespace, embedding_values @pytest.mark.skipif( diff --git a/tests/integration/data/test_upsert_sparse.py b/tests/integration/data/test_upsert_sparse.py index 2842bbfe4..b4511df3c 100644 --- a/tests/integration/data/test_upsert_sparse.py +++ b/tests/integration/data/test_upsert_sparse.py @@ -1,14 +1,14 @@ import pytest import random from pinecone import Vector, SparseValues -from ..helpers import poll_stats_for_namespace -from .utils import embedding_values +from ..helpers import poll_stats_for_namespace, embedding_values import logging logger = logging.getLogger(__name__) +@pytest.mark.skip(reason="Sparse indexes are not yet supported") class TestUpsertSparse: @pytest.mark.parametrize("use_nondefault_namespace", [True, False]) def test_upsert_sparse_to_namespace(self, sparse_idx, use_nondefault_namespace, namespace): diff --git a/tests/integration/data/test_weird_ids.py b/tests/integration/data/test_weird_ids.py index a5903e404..41fbd0fdc 100644 --- a/tests/integration/data/test_weird_ids.py +++ b/tests/integration/data/test_weird_ids.py @@ -1,8 +1,25 @@ import os import pytest -from .seed import weird_valid_ids, weird_invalid_ids +from ..helpers import random_string +from .seed import weird_valid_ids, weird_invalid_ids, setup_weird_ids_data +import logging +logger = logging.getLogger(__name__) + +@pytest.fixture(scope="session") +def weird_ids_namespace(): + return random_string(10) + + +@pytest.fixture(scope="class") +def seed_weird_ids(idx, weird_ids_namespace): + logger.info("Seeding data in weird ids namespace " + weird_ids_namespace) + setup_weird_ids_data(idx, weird_ids_namespace, True) + yield + + +@pytest.mark.usefixtures("seed_weird_ids") @pytest.mark.skipif( os.getenv("SKIP_WEIRD") == "true", reason="We don't need to run all of these every time" ) diff --git a/tests/integration/data/utils.py b/tests/integration/data/utils.py deleted file mode 100644 index 0a0905bf9..000000000 --- a/tests/integration/data/utils.py +++ /dev/null @@ -1,5 +0,0 @@ -import random - - -def embedding_values(dimension=2): - return [random.random() for _ in range(dimension)] diff --git a/tests/integration/helpers/__init__.py b/tests/integration/helpers/__init__.py index d5ffc930f..91f99733f 100644 --- a/tests/integration/helpers/__init__.py +++ b/tests/integration/helpers/__init__.py @@ -6,4 +6,5 @@ generate_collection_name, poll_stats_for_namespace, poll_fetch_for_ids_in_namespace, + embedding_values, ) diff --git a/tests/integration/helpers/helpers.py b/tests/integration/helpers/helpers.py index d22f4b8ed..a2e4d7b92 100644 --- a/tests/integration/helpers/helpers.py +++ b/tests/integration/helpers/helpers.py @@ -10,6 +10,10 @@ logger = logging.getLogger(__name__) +def embedding_values(dimension=2): + return [random.random() for _ in range(dimension)] + + def random_string(length): return "".join(random.choice(string.ascii_lowercase) for i in range(length)) From 0c0422bdca900eea018e7ddbe67434354ce1dac2 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 08:56:58 -0500 Subject: [PATCH 13/21] Fix more tests --- .github/workflows/testing-dependency.yaml | 2 +- pinecone/grpc/utils.py | 7 ++--- .../test_create_index_type_errors.py | 4 +-- tests/integration/data/test_fetch_future.py | 30 +++++++++++-------- tests/integration/data/test_list.py | 3 -- tests/integration/data/test_upsert_errors.py | 2 +- tests/integration/data/test_upsert_future.py | 16 ++++++---- 7 files changed, 35 insertions(+), 29 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index 42396ccc2..6422f6cdc 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -63,7 +63,7 @@ jobs: # - 4.1.0 - 4.3.3 protobuf_version: - - 4.25.3 + - 5.28 protoc-gen-openapiv2: - 0.0.1 googleapis_common_protos_version: diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index 8658fc73d..bd6540deb 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -9,11 +9,11 @@ Usage, ScoredVector, SparseValues, - FetchResponse, QueryResponse, IndexDescription as DescribeIndexStatsResponse, NamespaceSummary, ) +from pinecone.data.dataclasses import FetchResponse from google.protobuf.struct_pb2 import Struct @@ -55,10 +55,7 @@ def parse_fetch_response(response: Message): ) return FetchResponse( - vectors=vd, - namespace=namespace, - usage=parse_usage(json_response.get("usage", {})), - _check_type=False, + vectors=vd, namespace=namespace, usage=parse_usage(json_response.get("usage", {})) ) diff --git a/tests/integration/control/serverless/test_create_index_type_errors.py b/tests/integration/control/serverless/test_create_index_type_errors.py index 04cb99d53..9a2fc3cb2 100644 --- a/tests/integration/control/serverless/test_create_index_type_errors.py +++ b/tests/integration/control/serverless/test_create_index_type_errors.py @@ -1,11 +1,11 @@ import pytest -from pinecone import PineconeApiTypeError +from pinecone import PineconeApiException class TestCreateIndexTypeErrorCases: def test_create_index_with_invalid_str_dimension(self, client, create_sl_index_params): create_sl_index_params["dimension"] = "10" - with pytest.raises(PineconeApiTypeError): + with pytest.raises(PineconeApiException): client.create_index(**create_sl_index_params) def test_create_index_with_missing_dimension(self, client, create_sl_index_params): diff --git a/tests/integration/data/test_fetch_future.py b/tests/integration/data/test_fetch_future.py index 4817380c4..65f1607f8 100644 --- a/tests/integration/data/test_fetch_future.py +++ b/tests/integration/data/test_fetch_future.py @@ -1,6 +1,6 @@ import os import pytest -from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values +from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values, random_string from pinecone import Vector import logging @@ -10,8 +10,14 @@ from pinecone.grpc import PineconeGrpcFuture +@pytest.fixture(scope="session") +def fetch_namespace_future(): + return random_string(10) + + +@pytest.mark.usefixtures("fetch_namespace_future") @pytest.fixture(scope="class") -def seed_for_fetch(idx, namespace): +def seed_for_fetch(idx, fetch_namespace_future): # Upsert without metadata logger.info("Seeding vectors without metadata") idx.upsert( @@ -20,7 +26,7 @@ def seed_for_fetch(idx, namespace): ("2", embedding_values(2)), ("3", embedding_values(2)), ], - namespace=namespace, + namespace=fetch_namespace_future, ) # Upsert with metadata @@ -35,7 +41,7 @@ def seed_for_fetch(idx, namespace): id="6", values=embedding_values(2), metadata={"genre": "romance", "runtime": 240} ), ], - namespace=namespace, + namespace=fetch_namespace_future, ) # Upsert with dict @@ -45,11 +51,11 @@ def seed_for_fetch(idx, namespace): {"id": "8", "values": embedding_values(2)}, {"id": "9", "values": embedding_values(2)}, ], - namespace=namespace, + namespace=fetch_namespace_future, ) poll_fetch_for_ids_in_namespace( - idx, ids=["1", "2", "3", "4", "5", "6", "7", "8", "9"], namespace=namespace + idx, ids=["1", "2", "3", "4", "5", "6", "7", "8", "9"], namespace=fetch_namespace_future ) yield @@ -62,8 +68,8 @@ class TestFetchFuture: def setup_method(self): self.expected_dimension = 2 - def test_fetch_multiple_by_id(self, idx, namespace): - target_namespace = namespace + def test_fetch_multiple_by_id(self, idx, fetch_namespace_future): + target_namespace = fetch_namespace_future results = idx.fetch(ids=["1", "2", "4"], namespace=target_namespace, async_req=True) assert isinstance(results, PineconeGrpcFuture) @@ -91,8 +97,8 @@ def test_fetch_multiple_by_id(self, idx, namespace): assert results.vectors["1"].values is not None assert len(results.vectors["1"].values) == self.expected_dimension - def test_fetch_single_by_id(self, idx, namespace): - target_namespace = namespace + def test_fetch_single_by_id(self, idx, fetch_namespace_future): + target_namespace = fetch_namespace_future future = idx.fetch(ids=["1"], namespace=target_namespace, async_req=True) @@ -108,8 +114,8 @@ def test_fetch_single_by_id(self, idx, namespace): assert results.vectors["1"].values is not None assert len(results.vectors["1"].values) == self.expected_dimension - def test_fetch_nonexistent_id(self, idx, namespace): - target_namespace = namespace + def test_fetch_nonexistent_id(self, idx, fetch_namespace_future): + target_namespace = fetch_namespace_future # Fetch id that is missing future = idx.fetch(ids=["100"], namespace=target_namespace, async_req=True) diff --git a/tests/integration/data/test_list.py b/tests/integration/data/test_list.py index 72f16b762..039fe2956 100644 --- a/tests/integration/data/test_list.py +++ b/tests/integration/data/test_list.py @@ -1,6 +1,5 @@ import logging import pytest -from pinecone import Vector from ..helpers import poll_fetch_for_ids_in_namespace, embedding_values, random_string logger = logging.getLogger(__name__) @@ -40,7 +39,6 @@ def test_list_no_args(self, idx): assert results is not None assert results.namespace == "" assert results.vectors is not None - assert isinstance(results.vectors, list) # assert results.pagination == None def test_list_when_limit(self, idx, list_namespace): @@ -138,7 +136,6 @@ def test_list_then_fetch(self, idx, list_namespace): vectors.extend([v for _, v in result.vectors.items()]) assert len(vectors) == 11 - assert isinstance(vectors[0], Vector) assert set([v.id for v in vectors]) == set( ["99", "990", "991", "992", "993", "994", "995", "996", "997", "998", "999"] ) diff --git a/tests/integration/data/test_upsert_errors.py b/tests/integration/data/test_upsert_errors.py index 2ca422b73..e1f2fca5f 100644 --- a/tests/integration/data/test_upsert_errors.py +++ b/tests/integration/data/test_upsert_errors.py @@ -137,7 +137,7 @@ def test_upsert_fails_when_values_missing_dicts(self, idx): class TestUpsertFailsWhenValuesWrongType: def test_upsert_fails_when_values_wrong_type_objects(self, idx): - with pytest.raises(PineconeException): + with pytest.raises(Exception): idx.upsert(vectors=[Vector(id="1", values="abc"), Vector(id="2", values="def")]) def test_upsert_fails_when_values_wrong_type_tuples(self, idx): diff --git a/tests/integration/data/test_upsert_future.py b/tests/integration/data/test_upsert_future.py index 44b5a7463..7ca4b27e6 100644 --- a/tests/integration/data/test_upsert_future.py +++ b/tests/integration/data/test_upsert_future.py @@ -1,15 +1,21 @@ import pytest import os from pinecone import Vector, PineconeException -from ..helpers import poll_stats_for_namespace, embedding_values +from ..helpers import poll_stats_for_namespace, embedding_values, random_string +@pytest.fixture(scope="class") +def namespace_query_async(): + return random_string(10) + + +@pytest.mark.usefixtures("namespace_query_async") class TestUpsertWithAsyncReq: @pytest.mark.skipif( os.getenv("USE_GRPC") != "true", reason="PineconeGrpcFutures only returned from grpc client" ) - def test_upsert_to_namespace(self, idx, namespace): - target_namespace = namespace + def test_upsert_to_namespace(self, idx, namespace_query_async): + target_namespace = namespace_query_async # Upsert with tuples upsert1 = idx.upsert( @@ -63,8 +69,8 @@ def test_upsert_to_namespace(self, idx, namespace): @pytest.mark.skipif( os.getenv("USE_GRPC") != "true", reason="PineconeGrpcFutures only returned from grpc client" ) - def test_upsert_to_namespace_when_failed_req(self, idx, namespace): - target_namespace = namespace + def test_upsert_to_namespace_when_failed_req(self, idx, namespace_query_async): + target_namespace = namespace_query_async # Upsert with tuples upsert1 = idx.upsert( From 5f5a5d1956175cebf1ad3638d122278789ddc577 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 09:25:19 -0500 Subject: [PATCH 14/21] Adjust googleapis-common-protos for protobuf compat --- .github/workflows/testing-dependency.yaml | 2 +- poetry.lock | 2 +- pyproject.toml | 2 +- .../control/serverless/test_create_index_type_errors.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index 6422f6cdc..de77c0acc 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -67,7 +67,7 @@ jobs: protoc-gen-openapiv2: - 0.0.1 googleapis_common_protos_version: - - 1.62.0 + - 1.63.0 steps: - uses: actions/checkout@v4 - uses: ./.github/actions/test-dependency-grpc diff --git a/poetry.lock b/poetry.lock index c4b2b6e10..9f836573c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1628,4 +1628,4 @@ grpc = ["googleapis-common-protos", "grpcio", "grpcio", "lz4", "protobuf", "prot [metadata] lock-version = "2.0" python-versions = "^3.8" -content-hash = "648e5233ed7f5cb5ef7b152a01a35eef44c1f8994ea54dc3241131fc5aa4a1f1" +content-hash = "4d96e143202dabbbb5e19d88ea0a0f8b607a0ade2f0330b3bee3e5b975186a3a" diff --git a/pyproject.toml b/pyproject.toml index b28d14818..ef0e7aa83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ grpcio = [ { version = ">=1.44.0", optional = true, python = "^3.8,<3.11" }, { version = ">=1.59.0", optional = true, python = "^3.11" } ] -googleapis-common-protos = { version = ">=1.53.0", optional = true } +googleapis-common-protos = { version = ">=1.63.0", optional = true } lz4 = { version = ">=3.1.3", optional = true } protobuf = { version = "^5.28", optional = true } protoc-gen-openapiv2 = {version = "^0.0.1", optional = true } diff --git a/tests/integration/control/serverless/test_create_index_type_errors.py b/tests/integration/control/serverless/test_create_index_type_errors.py index 9a2fc3cb2..93a2d3ba5 100644 --- a/tests/integration/control/serverless/test_create_index_type_errors.py +++ b/tests/integration/control/serverless/test_create_index_type_errors.py @@ -10,5 +10,5 @@ def test_create_index_with_invalid_str_dimension(self, client, create_sl_index_p def test_create_index_with_missing_dimension(self, client, create_sl_index_params): del create_sl_index_params["dimension"] - with pytest.raises(TypeError): + with pytest.raises(PineconeApiException): client.create_index(**create_sl_index_params) From 84248fcbc32653ea4953a160e6c1e9571308600d Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 10:06:48 -0500 Subject: [PATCH 15/21] Iterate on grpc deps --- .github/workflows/testing-dependency.yaml | 3 +-- poetry.lock | 2 +- pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index de77c0acc..d847163ca 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -63,7 +63,7 @@ jobs: # - 4.1.0 - 4.3.3 protobuf_version: - - 5.28 + - 5.29.1 protoc-gen-openapiv2: - 0.0.1 googleapis_common_protos_version: @@ -79,7 +79,6 @@ jobs: lz4_version: '${{ matrix.lz4_version }}' protobuf_version: '${{ matrix.protobuf_version }}' googleapis_common_protos_version: '${{ matrix.googleapis_common_protos_version }}' - DD_TAGS: 'test.configuration.python:${{ matrix.python_version}},test.configuration.grpcio:${{ matrix.grpcio_version }},test.configuration.lz4:${{ matrix.lz4_version }},test.configuration.protobuf:${{ matrix.protobuf_version }},test.configuration.googleapis_common_protos:${{ matrix.googleapis_common_protos_version }}' dependency-matrix-grpc-312: name: Deps (GRPC) diff --git a/poetry.lock b/poetry.lock index 9f836573c..2f34d0b5c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1628,4 +1628,4 @@ grpc = ["googleapis-common-protos", "grpcio", "grpcio", "lz4", "protobuf", "prot [metadata] lock-version = "2.0" python-versions = "^3.8" -content-hash = "4d96e143202dabbbb5e19d88ea0a0f8b607a0ade2f0330b3bee3e5b975186a3a" +content-hash = "82846dc34d7cd2fdadd6d7a3100e79692b3c563393de1b6f9ffd15cac32d0e0a" diff --git a/pyproject.toml b/pyproject.toml index ef0e7aa83..6a36794f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ grpcio = [ ] googleapis-common-protos = { version = ">=1.63.0", optional = true } lz4 = { version = ">=3.1.3", optional = true } -protobuf = { version = "^5.28", optional = true } +protobuf = { version = "^5.29", optional = true } protoc-gen-openapiv2 = {version = "^0.0.1", optional = true } pinecone-plugin-interface = "^0.0.7" pinecone-plugin-inference = "^2.0.0" From df0e8e4d5d952df82203b3a7d41b4d79ce072a64 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 10:37:50 -0500 Subject: [PATCH 16/21] Fix sparse query --- pinecone/data/request_factory.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py index de76530e9..7c63a2dd8 100644 --- a/pinecone/data/request_factory.py +++ b/pinecone/data/request_factory.py @@ -10,6 +10,7 @@ ) from ..utils import parse_non_empty_args from .vector_factory import VectorFactory +from .sparse_values_factory import SparseValuesFactory from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS from .types import ( VectorTypedDict, @@ -66,7 +67,7 @@ def query_request( if vector is not None and id is not None: raise ValueError("Cannot specify both `id` and `vector`") - sparse_vector = parse_sparse_values_arg(sparse_vector) + sparse_vector = SparseValuesFactory.build(sparse_vector) args_dict = parse_non_empty_args( [ ("vector", vector), From c618fff7370ead159b3f792822f418ac7be8bd44 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 10:53:32 -0500 Subject: [PATCH 17/21] Fix sparse query types --- pinecone/data/request_factory.py | 30 ++++---------------------- pinecone/data/sparse_values_factory.py | 5 +++-- 2 files changed, 7 insertions(+), 28 deletions(-) diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py index 7c63a2dd8..acf564483 100644 --- a/pinecone/data/request_factory.py +++ b/pinecone/data/request_factory.py @@ -25,28 +25,6 @@ logger = logging.getLogger(__name__) -def parse_sparse_values_arg( - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]], -) -> Optional[SparseValues]: - if sparse_values is None: - return None - - if isinstance(sparse_values, SparseValues): - return sparse_values - - if ( - not isinstance(sparse_values, dict) - or "indices" not in sparse_values - or "values" not in sparse_values - ): - raise ValueError( - "Invalid sparse values argument. Expected a dict of: {'indices': List[int], 'values': List[float]}." - f"Received: {sparse_values}" - ) - - return SparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) - - def non_openapi_kwargs(kwargs): return {k: v for k, v in kwargs.items() if k not in OPENAPI_ENDPOINT_PARAMS} @@ -67,7 +45,7 @@ def query_request( if vector is not None and id is not None: raise ValueError("Cannot specify both `id` and `vector`") - sparse_vector = SparseValuesFactory.build(sparse_vector) + sparse_vector_normalized = SparseValuesFactory.build(sparse_vector) args_dict = parse_non_empty_args( [ ("vector", vector), @@ -78,7 +56,7 @@ def query_request( ("filter", filter), ("include_values", include_values), ("include_metadata", include_metadata), - ("sparse_vector", sparse_vector), + ("sparse_vector", sparse_vector_normalized), ] ) @@ -131,13 +109,13 @@ def update_request( **kwargs, ) -> UpdateRequest: _check_type = kwargs.pop("_check_type", False) - sparse_values = parse_sparse_values_arg(sparse_values) + sparse_values_normalized = SparseValuesFactory.build(sparse_values) args_dict = parse_non_empty_args( [ ("values", values), ("set_metadata", set_metadata), ("namespace", namespace), - ("sparse_values", sparse_values), + ("sparse_values", sparse_values_normalized), ] ) diff --git a/pinecone/data/sparse_values_factory.py b/pinecone/data/sparse_values_factory.py index dc043b976..5d07136eb 100644 --- a/pinecone/data/sparse_values_factory.py +++ b/pinecone/data/sparse_values_factory.py @@ -1,5 +1,5 @@ from collections.abc import Mapping -from typing import Union, Dict, Optional +from typing import Union, Optional from ..utils import convert_to_list @@ -10,6 +10,7 @@ ) from .dataclasses import SparseValues +from .types import SparseVectorTypedDict from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues @@ -18,7 +19,7 @@ class SparseValuesFactory: @staticmethod def build( - input: Union[Dict, Optional[SparseValues], OpenApiSparseValues], + input: Optional[Union[SparseValues, OpenApiSparseValues, SparseVectorTypedDict]], ) -> Optional[OpenApiSparseValues]: if input is None: return input From 2770806ffd5dff6027ae02ce7c30e903c363b342 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 11:32:51 -0500 Subject: [PATCH 18/21] Iterate on grpc deps --- .github/workflows/testing-dependency.yaml | 2 +- poetry.lock | 2 +- pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index d847163ca..de5efdcde 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -67,7 +67,7 @@ jobs: protoc-gen-openapiv2: - 0.0.1 googleapis_common_protos_version: - - 1.63.0 + - 1.66.0 steps: - uses: actions/checkout@v4 - uses: ./.github/actions/test-dependency-grpc diff --git a/poetry.lock b/poetry.lock index 2f34d0b5c..6ef2fdab4 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1628,4 +1628,4 @@ grpc = ["googleapis-common-protos", "grpcio", "grpcio", "lz4", "protobuf", "prot [metadata] lock-version = "2.0" python-versions = "^3.8" -content-hash = "82846dc34d7cd2fdadd6d7a3100e79692b3c563393de1b6f9ffd15cac32d0e0a" +content-hash = "71416dd3b587362076f8adc2998e03dd02c4d0be13b37244a46da7f935078c3e" diff --git a/pyproject.toml b/pyproject.toml index 6a36794f2..6d244e117 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ grpcio = [ { version = ">=1.44.0", optional = true, python = "^3.8,<3.11" }, { version = ">=1.59.0", optional = true, python = "^3.11" } ] -googleapis-common-protos = { version = ">=1.63.0", optional = true } +googleapis-common-protos = { version = ">=1.66.0", optional = true } lz4 = { version = ">=3.1.3", optional = true } protobuf = { version = "^5.29", optional = true } protoc-gen-openapiv2 = {version = "^0.0.1", optional = true } From 5aa290ef61f690bc40adb4d0ccc365212e0e4edb Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 11:38:50 -0500 Subject: [PATCH 19/21] Fix integration test --- .../control/serverless/test_create_index_type_errors.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/control/serverless/test_create_index_type_errors.py b/tests/integration/control/serverless/test_create_index_type_errors.py index 93a2d3ba5..4473d8f15 100644 --- a/tests/integration/control/serverless/test_create_index_type_errors.py +++ b/tests/integration/control/serverless/test_create_index_type_errors.py @@ -1,11 +1,11 @@ import pytest -from pinecone import PineconeApiException +from pinecone import PineconeApiException, PineconeApiTypeError class TestCreateIndexTypeErrorCases: def test_create_index_with_invalid_str_dimension(self, client, create_sl_index_params): create_sl_index_params["dimension"] = "10" - with pytest.raises(PineconeApiException): + with pytest.raises(PineconeApiTypeError): client.create_index(**create_sl_index_params) def test_create_index_with_missing_dimension(self, client, create_sl_index_params): From 0d09933e613c59115c5c6d58d7a6d266e4acc48d Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 16:45:11 -0500 Subject: [PATCH 20/21] Adjust grpc dep testing config --- .github/workflows/testing-dependency.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index de5efdcde..fd0e9e38d 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -98,11 +98,11 @@ jobs: - 3.1.3 - 4.3.3 protobuf_version: - - 4.25.3 + - 5.29.1 protoc-gen-openapiv2: - 0.0.1 googleapis_common_protos_version: - - 1.62.0 + - 1.66.0 steps: - uses: actions/checkout@v4 - uses: ./.github/actions/test-dependency-grpc From 3f134b4dd9f51111343c72528316dfbc316dfab7 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 17 Dec 2024 16:46:12 -0500 Subject: [PATCH 21/21] Adjust test configuration --- .github/workflows/testing-dependency.yaml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/testing-dependency.yaml b/.github/workflows/testing-dependency.yaml index fd0e9e38d..c3686b82d 100644 --- a/.github/workflows/testing-dependency.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -114,7 +114,6 @@ jobs: lz4_version: '${{ matrix.lz4_version }}' protobuf_version: '${{ matrix.protobuf_version }}' googleapis_common_protos_version: '${{ matrix.googleapis_common_protos_version }}' - DD_TAGS: 'test.configuration.python:${{ matrix.python_version}},test.configuration.grpcio:${{ matrix.grpcio_version }},test.configuration.lz4:${{ matrix.lz4_version }},test.configuration.protobuf:${{ matrix.protobuf_version }},test.configuration.googleapis_common_protos:${{ matrix.googleapis_common_protos_version }}' dependency-matrix-rest: name: Deps (REST) @@ -140,7 +139,6 @@ jobs: index_name: '${{ needs.dependency-matrix-setup.outputs.index_name }}' PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' urllib3_version: '${{ matrix.urllib3_version }}' - DD_TAGS: 'test.configuration.python:${{ matrix.python_version}},test.configuration.urllib3:${{ matrix.urllib3_version }}' dependency-matrix-rest-312: name: Deps (REST) @@ -165,7 +163,6 @@ jobs: index_name: '${{ needs.dependency-matrix-setup.outputs.index_name }}' PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' urllib3_version: '${{ matrix.urllib3_version }}' - DD_TAGS: 'test.configuration.python:${{ matrix.python_version}},test.configuration.urllib3:${{ matrix.urllib3_version }}' deps-cleanup: name: Deps cleanup