From 17e0566dd8643264dde1c866022cc45eda8a9b56 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 16 Oct 2023 18:07:56 -0400 Subject: [PATCH 01/39] Update generated client code (#215) ## Problem We need to update the generated core module to reflect upcoming API changes ## Solution - Migrate from v5 to v7 openapi generator to avoid generating code with deprecated urllib3 usage. - Regenerate contents of `pinecone.core` using pinecone-protos (private) repo. - Refactor to move all non-generated items out from under `pinecone.core`. These never should have been under `pinecone.core` in the first place. - Added `pinecone.utils` - Added `pinecone.grpc` to hold `GRPCIndex` and related code. - Add new dependencies required by updated generated code (`pydantic` for typechecking, `aenum` for enums) - Disable legacy `integ` tests which won't work until we refactor configuration. ## Type of Change - [x] New feature (non-breaking change which adds functionality) --- pinecone/__init__.py | 4 +- pinecone/config.py | 23 +- pinecone/core/__init__.py | 1 - pinecone/core/api_action.py | 37 - pinecone/core/api_base.py | 35 - pinecone/core/client/__init__.py | 53 +- pinecone/core/client/api/__init__.py | 8 +- .../core/client/api/index_operations_api.py | 2248 ++++++++++------- .../core/client/api/vector_operations_api.py | 1915 ++++++++------ pinecone/core/client/api_client.py | 834 +++--- pinecone/core/client/api_response.py | 22 + pinecone/core/client/apis/__init__.py | 17 - pinecone/core/client/configuration.py | 122 +- pinecone/core/client/exceptions.py | 36 +- pinecone/core/client/model/__init__.py | 5 - .../core/client/model/approximated_config.py | 275 -- pinecone/core/client/model/collection_meta.py | 279 -- .../client/model/create_collection_request.py | 283 --- pinecone/core/client/model/create_request.py | 322 --- pinecone/core/client/model/delete_request.py | 285 --- .../model/describe_index_stats_request.py | 271 -- .../model/describe_index_stats_response.py | 291 --- pinecone/core/client/model/fetch_response.py | 283 --- pinecone/core/client/model/hnsw_config.py | 283 --- pinecone/core/client/model/index_meta.py | 279 -- .../core/client/model/index_meta_database.py | 319 --- .../model/index_meta_database_status.py | 283 --- .../core/client/model/index_meta_status.py | 283 --- .../core/client/model/namespace_summary.py | 271 -- pinecone/core/client/model/patch_request.py | 275 -- pinecone/core/client/model/protobuf_any.py | 275 -- .../core/client/model/protobuf_null_value.py | 293 --- pinecone/core/client/model/query_request.py | 329 --- pinecone/core/client/model/query_response.py | 289 --- pinecone/core/client/model/query_vector.py | 307 --- pinecone/core/client/model/rpc_status.py | 287 --- pinecone/core/client/model/scored_vector.py | 306 --- .../core/client/model/single_query_results.py | 283 --- pinecone/core/client/model/sparse_values.py | 286 --- pinecone/core/client/model/update_request.py | 307 --- pinecone/core/client/model/upsert_request.py | 291 --- pinecone/core/client/model/upsert_response.py | 271 -- pinecone/core/client/model/vector.py | 305 --- pinecone/core/client/model_utils.py | 1884 -------------- pinecone/core/client/models/__init__.py | 79 +- .../core/client/models/approximated_config.py | 74 + .../core/client/models/collection_meta.py | 79 + .../models/create_collection_request.py | 68 + pinecone/core/client/models/create_request.py | 149 ++ .../models/create_request_index_config.py | 140 + pinecone/core/client/models/delete_request.py | 85 + .../models/describe_index_stats_request.py | 71 + .../models/describe_index_stats_response.py | 95 + pinecone/core/client/models/fetch_response.py | 84 + pinecone/core/client/models/hnsw_config.py | 78 + pinecone/core/client/models/index_meta.py | 83 + .../core/client/models/index_meta_database.py | 110 + .../index_meta_database_index_config.py | 140 + .../core/client/models/index_meta_status.py | 90 + .../client/models/list_indexes200_response.py | 82 + .../core/client/models/namespace_summary.py | 72 + pinecone/core/client/models/patch_request.py | 72 + pinecone/core/client/models/protobuf_any.py | 69 + .../core/client/models/protobuf_null_value.py | 35 + pinecone/core/client/models/query_request.py | 134 + pinecone/core/client/models/query_response.py | 98 + pinecone/core/client/models/query_vector.py | 93 + pinecone/core/client/models/rpc_status.py | 86 + pinecone/core/client/models/scored_vector.py | 91 + .../client/models/single_query_results.py | 84 + pinecone/core/client/models/sparse_values.py | 72 + pinecone/core/client/models/update_request.py | 88 + pinecone/core/client/models/upsert_request.py | 86 + .../core/client/models/upsert_response.py | 70 + pinecone/core/client/models/vector.py | 86 + pinecone/core/client/py.typed | 0 pinecone/core/client/rest.py | 58 +- pinecone/core/exceptions.py | 6 - pinecone/core/grpc/__init__.py | 1 - pinecone/core/grpc/protos/__init__.py | 1 - pinecone/exceptions.py | 7 +- pinecone/grpc/__init__.py | 0 pinecone/{core => }/grpc/index_grpc.py | 22 +- .../grpc/protos/vector_column_service_pb2.py | 2 +- .../grpc/protos/vector_column_service_pb2.pyi | 2 +- .../protos/vector_column_service_pb2_grpc.py | 2 +- pinecone/{core => }/grpc/retry.py | 2 +- pinecone/index.py | 14 +- pinecone/info.py | 35 - pinecone/manage.py | 17 +- pinecone/{core => }/utils/__init__.py | 8 +- pinecone/{core => }/utils/constants.py | 4 +- pinecone/{core => }/utils/error_handling.py | 9 +- poetry.lock | 108 +- pyproject.toml | 4 +- tests/integ/test_index.py | 137 +- tests/unit/test_config.py | 180 +- tests/unit/test_grpc_index.py | 716 +++--- tests/unit/test_index.py | 533 ++-- tests/unit/test_manage.py | 2 +- 100 files changed, 6845 insertions(+), 13123 deletions(-) delete mode 100644 pinecone/core/api_action.py delete mode 100644 pinecone/core/api_base.py create mode 100644 pinecone/core/client/api_response.py delete mode 100644 pinecone/core/client/apis/__init__.py delete mode 100644 pinecone/core/client/model/__init__.py delete mode 100644 pinecone/core/client/model/approximated_config.py delete mode 100644 pinecone/core/client/model/collection_meta.py delete mode 100644 pinecone/core/client/model/create_collection_request.py delete mode 100644 pinecone/core/client/model/create_request.py delete mode 100644 pinecone/core/client/model/delete_request.py delete mode 100644 pinecone/core/client/model/describe_index_stats_request.py delete mode 100644 pinecone/core/client/model/describe_index_stats_response.py delete mode 100644 pinecone/core/client/model/fetch_response.py delete mode 100644 pinecone/core/client/model/hnsw_config.py delete mode 100644 pinecone/core/client/model/index_meta.py delete mode 100644 pinecone/core/client/model/index_meta_database.py delete mode 100644 pinecone/core/client/model/index_meta_database_status.py delete mode 100644 pinecone/core/client/model/index_meta_status.py delete mode 100644 pinecone/core/client/model/namespace_summary.py delete mode 100644 pinecone/core/client/model/patch_request.py delete mode 100644 pinecone/core/client/model/protobuf_any.py delete mode 100644 pinecone/core/client/model/protobuf_null_value.py delete mode 100644 pinecone/core/client/model/query_request.py delete mode 100644 pinecone/core/client/model/query_response.py delete mode 100644 pinecone/core/client/model/query_vector.py delete mode 100644 pinecone/core/client/model/rpc_status.py delete mode 100644 pinecone/core/client/model/scored_vector.py delete mode 100644 pinecone/core/client/model/single_query_results.py delete mode 100644 pinecone/core/client/model/sparse_values.py delete mode 100644 pinecone/core/client/model/update_request.py delete mode 100644 pinecone/core/client/model/upsert_request.py delete mode 100644 pinecone/core/client/model/upsert_response.py delete mode 100644 pinecone/core/client/model/vector.py delete mode 100644 pinecone/core/client/model_utils.py create mode 100644 pinecone/core/client/models/approximated_config.py create mode 100644 pinecone/core/client/models/collection_meta.py create mode 100644 pinecone/core/client/models/create_collection_request.py create mode 100644 pinecone/core/client/models/create_request.py create mode 100644 pinecone/core/client/models/create_request_index_config.py create mode 100644 pinecone/core/client/models/delete_request.py create mode 100644 pinecone/core/client/models/describe_index_stats_request.py create mode 100644 pinecone/core/client/models/describe_index_stats_response.py create mode 100644 pinecone/core/client/models/fetch_response.py create mode 100644 pinecone/core/client/models/hnsw_config.py create mode 100644 pinecone/core/client/models/index_meta.py create mode 100644 pinecone/core/client/models/index_meta_database.py create mode 100644 pinecone/core/client/models/index_meta_database_index_config.py create mode 100644 pinecone/core/client/models/index_meta_status.py create mode 100644 pinecone/core/client/models/list_indexes200_response.py create mode 100644 pinecone/core/client/models/namespace_summary.py create mode 100644 pinecone/core/client/models/patch_request.py create mode 100644 pinecone/core/client/models/protobuf_any.py create mode 100644 pinecone/core/client/models/protobuf_null_value.py create mode 100644 pinecone/core/client/models/query_request.py create mode 100644 pinecone/core/client/models/query_response.py create mode 100644 pinecone/core/client/models/query_vector.py create mode 100644 pinecone/core/client/models/rpc_status.py create mode 100644 pinecone/core/client/models/scored_vector.py create mode 100644 pinecone/core/client/models/single_query_results.py create mode 100644 pinecone/core/client/models/sparse_values.py create mode 100644 pinecone/core/client/models/update_request.py create mode 100644 pinecone/core/client/models/upsert_request.py create mode 100644 pinecone/core/client/models/upsert_response.py create mode 100644 pinecone/core/client/models/vector.py create mode 100644 pinecone/core/client/py.typed delete mode 100644 pinecone/core/exceptions.py delete mode 100644 pinecone/core/grpc/__init__.py delete mode 100644 pinecone/core/grpc/protos/__init__.py create mode 100644 pinecone/grpc/__init__.py rename pinecone/{core => }/grpc/index_grpc.py (98%) rename pinecone/{core => }/grpc/protos/vector_column_service_pb2.py (99%) rename pinecone/{core => }/grpc/protos/vector_column_service_pb2.pyi (99%) rename pinecone/{core => }/grpc/protos/vector_column_service_pb2_grpc.py (99%) rename pinecone/{core => }/grpc/retry.py (99%) delete mode 100644 pinecone/info.py rename pinecone/{core => }/utils/__init__.py (93%) rename pinecone/{core => }/utils/constants.py (87%) rename pinecone/{core => }/utils/error_handling.py (75%) diff --git a/pinecone/__init__.py b/pinecone/__init__.py index f3909e0b8..8ade68bca 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -1,15 +1,13 @@ """ .. include:: ../README.md """ -from pinecone.core.utils.constants import CLIENT_VERSION as __version__ from .config import * from .exceptions import * -from .info import * from .manage import * from .index import * try: - from .core.grpc.index_grpc import * + from .grpc.index_grpc import * except ImportError: pass # ignore for non-[grpc] installations diff --git a/pinecone/config.py b/pinecone/config.py index dfde4b97f..f4bc276c3 100644 --- a/pinecone/config.py +++ b/pinecone/config.py @@ -11,9 +11,8 @@ from urllib3.connection import HTTPConnection from pinecone.core.client.exceptions import ApiKeyError -from pinecone.core.api_action import ActionAPI, WhoAmIResponse -from pinecone.core.utils import warn_deprecated, check_kwargs -from pinecone.core.utils.constants import ( +from pinecone.utils import warn_deprecated, check_kwargs +from pinecone.utils.constants import ( CLIENT_VERSION, PARENT_LOGGER_NAME, DEFAULT_PARENT_LOGGER_LEVEL, @@ -93,21 +92,6 @@ def reset(self, config_file=None, **kwargs): self._config = config - # load project_name etc. from whoami api - action_api = ActionAPI(host=config.controller_host, api_key=config.api_key) - try: - whoami_response = action_api.whoami() - except requests.exceptions.RequestException: - # proceed with default values; reset() may be called later w/ correct values - whoami_response = WhoAmIResponse() - - if not self._config.project_name: - config = config._replace( - **self._preprocess_and_validate_config({"project_name": whoami_response.projectname}) - ) - - self._config = config - # Set OpenAPI client config default_openapi_config = OpenApiConfiguration.get_default_copy() default_openapi_config.ssl_ca_cert = certifi.where() @@ -239,7 +223,6 @@ def init( api_key: str = None, host: str = None, environment: str = None, - project_name: str = None, log_level: str = None, openapi_config: OpenApiConfiguration = None, config: str = "~/.pinecone", @@ -250,14 +233,12 @@ def init( :param api_key: Required if not set in config file or by environment variable ``PINECONE_API_KEY``. :param host: Optional. Controller host. :param environment: Optional. Deployment environment. - :param project_name: Optional. Pinecone project name. Overrides the value that is otherwise looked up and used from the Pinecone backend. :param openapi_config: Optional. Set OpenAPI client configuration. :param config: Optional. An INI configuration file. :param log_level: Deprecated since v2.0.2 [Will be removed in v3.0.0]; use the standard logging module to manage logger "pinecone" instead. """ check_kwargs(init, kwargs) Config.reset( - project_name=project_name, api_key=api_key, controller_host=host, environment=environment, diff --git a/pinecone/core/__init__.py b/pinecone/core/__init__.py index 8b1378917..e69de29bb 100644 --- a/pinecone/core/__init__.py +++ b/pinecone/core/__init__.py @@ -1 +0,0 @@ - diff --git a/pinecone/core/api_action.py b/pinecone/core/api_action.py deleted file mode 100644 index 12fc74f37..000000000 --- a/pinecone/core/api_action.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import NamedTuple -from pinecone.core.api_base import BaseAPI - -__all__ = ["ActionAPI", "VersionResponse", "WhoAmIResponse"] - -from pinecone.core.utils import get_version - - -class WhoAmIResponse(NamedTuple): - username: str = "UNKNOWN" - user_label: str = "UNKNOWN" - projectname: str = "UNKNOWN" - - -class VersionResponse(NamedTuple): - server: str - client: str - - -class ActionAPI(BaseAPI): - """User related API calls.""" - - client_version = get_version() - - def whoami(self) -> WhoAmIResponse: - """Returns user information.""" - response = self.get("/actions/whoami") - return WhoAmIResponse( - username=response.get("user_name", "UNDEFINED"), - projectname=response.get("project_name", "UNDEFINED"), - user_label=response.get("user_label", "UNDEFINED"), - ) - - def version(self) -> VersionResponse: - """Returns version information.""" - response = self.get("/actions/version") - return VersionResponse(server=response.get("version", "UNKNOWN"), client=self.client_version) diff --git a/pinecone/core/api_base.py b/pinecone/core/api_base.py deleted file mode 100644 index 93a3a7aec..000000000 --- a/pinecone/core/api_base.py +++ /dev/null @@ -1,35 +0,0 @@ -import requests -from requests.exceptions import HTTPError - - -class BaseAPI: - """Base class for HTTP API calls.""" - - def __init__(self, host: str, api_key: str = None): - self.host = host - self.api_key = api_key - - @property - def headers(self): - return {"api-key": self.api_key} - - def _send_request(self, request_handler, url, **kwargs): - response = request_handler("{0}{1}".format(self.host, url), headers=self.headers, **kwargs) - try: - response.raise_for_status() - except HTTPError as e: - e.args = e.args + (response.text,) - raise e - return response.json() - - def get(self, url: str, params: dict = None): - return self._send_request(requests.get, url, params=params) - - def post(self, url: str, json: dict = None): - return self._send_request(requests.post, url, json=json) - - def patch(self, url: str, json: dict = None): - return self._send_request(requests.patch, url, json=json) - - def delete(self, url: str): - return self._send_request(requests.delete, url) diff --git a/pinecone/core/client/__init__.py b/pinecone/core/client/__init__.py index 584d1219b..3e4f7ad7e 100644 --- a/pinecone/core/client/__init__.py +++ b/pinecone/core/client/__init__.py @@ -1,28 +1,65 @@ +# coding: utf-8 + # flake8: noqa """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 __version__ = "1.0.0" +# import apis into sdk package +from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api.vector_operations_api import VectorOperationsApi + # import ApiClient +from pinecone.core.client.api_response import ApiResponse from pinecone.core.client.api_client import ApiClient - -# import Configuration from pinecone.core.client.configuration import Configuration - -# import exceptions from pinecone.core.client.exceptions import OpenApiException -from pinecone.core.client.exceptions import ApiAttributeError from pinecone.core.client.exceptions import ApiTypeError from pinecone.core.client.exceptions import ApiValueError from pinecone.core.client.exceptions import ApiKeyError +from pinecone.core.client.exceptions import ApiAttributeError from pinecone.core.client.exceptions import ApiException + +# import models into sdk package +from pinecone.core.client.models.approximated_config import ApproximatedConfig +from pinecone.core.client.models.collection_meta import CollectionMeta +from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.core.client.models.create_request import CreateRequest +from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig +from pinecone.core.client.models.delete_request import DeleteRequest +from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.models.fetch_response import FetchResponse +from pinecone.core.client.models.hnsw_config import HnswConfig +from pinecone.core.client.models.index_meta import IndexMeta +from pinecone.core.client.models.index_meta_database import IndexMetaDatabase +from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig +from pinecone.core.client.models.index_meta_status import IndexMetaStatus +from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response +from pinecone.core.client.models.namespace_summary import NamespaceSummary +from pinecone.core.client.models.patch_request import PatchRequest +from pinecone.core.client.models.protobuf_any import ProtobufAny +from pinecone.core.client.models.protobuf_null_value import ProtobufNullValue +from pinecone.core.client.models.query_request import QueryRequest +from pinecone.core.client.models.query_response import QueryResponse +from pinecone.core.client.models.query_vector import QueryVector +from pinecone.core.client.models.rpc_status import RpcStatus +from pinecone.core.client.models.scored_vector import ScoredVector +from pinecone.core.client.models.single_query_results import SingleQueryResults +from pinecone.core.client.models.sparse_values import SparseValues +from pinecone.core.client.models.update_request import UpdateRequest +from pinecone.core.client.models.upsert_request import UpsertRequest +from pinecone.core.client.models.upsert_response import UpsertResponse +from pinecone.core.client.models.vector import Vector diff --git a/pinecone/core/client/api/__init__.py b/pinecone/core/client/api/__init__.py index 14e304372..dc3b0a5bf 100644 --- a/pinecone/core/client/api/__init__.py +++ b/pinecone/core/client/api/__init__.py @@ -1,3 +1,5 @@ -# do not import all apis into this module because that uses a lot of memory and stack frames -# if you need the ability to import all apis from one package, import them with -# from pinecone.core.client.apis import IndexOperationsApi +# flake8: noqa + +# import apis into api package +from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/client/api/index_operations_api.py b/pinecone/core/client/api/index_operations_api.py index 5da15f3e1..5c33010fc 100644 --- a/pinecone/core/client/api/index_operations_api.py +++ b/pinecone/core/client/api/index_operations_api.py @@ -1,903 +1,1411 @@ +# coding: utf-8 + """ - Pinecone index operations API + Pinecone API - # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + The version of the OpenAPI document: version not set Contact: support@pinecone.io -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.client.model_utils import ( # noqa: F401 - check_allowed_values, - check_validations, - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.client.model.collection_meta import CollectionMeta -from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_request import CreateRequest -from pinecone.core.client.model.index_meta import IndexMeta -from pinecone.core.client.model.patch_request import PatchRequest - - -class IndexOperationsApi(object): +import io +import warnings + +from pydantic import validate_arguments, ValidationError + +from typing_extensions import Annotated +from pydantic import Field, StrictStr + +from typing import List, Optional + +from pinecone.core.client.models.collection_meta import CollectionMeta +from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.core.client.models.create_request import CreateRequest +from pinecone.core.client.models.index_meta import IndexMeta +from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response +from pinecone.core.client.models.patch_request import PatchRequest + +from pinecone.core.client.api_client import ApiClient +from pinecone.core.client.api_response import ApiResponse +from pinecone.core.client.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class IndexOperationsApi: """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def __configure_index(self, index_name, **kwargs): - """configure_index # noqa: E501 - - This operation specifies the pod type and number of replicas for an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.configure_index(index_name, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index - - Keyword Args: - patch_request (PatchRequest): The desired pod type and replica configuration for the index.. [optional] - _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: - str - 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["index_name"] = index_name - return self.call_with_http_info(**kwargs) - - self.configure_index = _Endpoint( - settings={ - "response_type": (str,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/databases/{indexName}", - "operation_id": "configure_index", - "http_method": "PATCH", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "index_name", - "patch_request", - ], - "required": [ - "index_name", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "index_name": (str,), - "patch_request": (PatchRequest,), - }, - "attribute_map": { - "index_name": "indexName", - }, - "location_map": { - "index_name": "path", - "patch_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["text/plain"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__configure_index, + @validate_arguments + def configure_index( + self, + index_name: Annotated[StrictStr, Field(..., description="The name of the index")], + patch_request: Annotated[ + Optional[PatchRequest], Field(description="The desired pod type and replica configuration for the index.") + ] = None, + **kwargs, + ) -> IndexMeta: # noqa: E501 + """configure_index # noqa: E501 + + This operation specifies the pod type and number of replicas for an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.configure_index(index_name, patch_request, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param patch_request: The desired pod type and replica configuration for the index. + :type patch_request: PatchRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: IndexMeta + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the configure_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.configure_index_with_http_info(index_name, patch_request, **kwargs) # noqa: E501 + + @validate_arguments + def configure_index_with_http_info( + self, + index_name: Annotated[StrictStr, Field(..., description="The name of the index")], + patch_request: Annotated[ + Optional[PatchRequest], Field(description="The desired pod type and replica configuration for the index.") + ] = None, + **kwargs, + ) -> ApiResponse: # noqa: E501 + """configure_index # noqa: E501 + + This operation specifies the pod type and number of replicas for an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.configure_index_with_http_info(index_name, patch_request, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param patch_request: The desired pod type and replica configuration for the index. + :type patch_request: PatchRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["index_name", "patch_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method configure_index" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params["index_name"]: + _path_params["indexName"] = _params["index_name"] + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["patch_request"] is not None: + _body_params = _params["patch_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "202": "IndexMeta", + "400": None, + "404": None, + "500": None, + } + + return self.api_client.call_api( + "/databases/{indexName}", + "PATCH", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def create_collection( + self, create_collection_request: Optional[CreateCollectionRequest] = None, **kwargs + ) -> str: # noqa: E501 + """create_collection # noqa: E501 + + This operation creates a Pinecone collection. # 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_collection(create_collection_request, async_req=True) + >>> result = thread.get() + + :param create_collection_request: + :type create_collection_request: CreateCollectionRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the create_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.create_collection_with_http_info(create_collection_request, **kwargs) # noqa: E501 + + @validate_arguments + def create_collection_with_http_info( + self, create_collection_request: Optional[CreateCollectionRequest] = None, **kwargs + ) -> ApiResponse: # noqa: E501 + """create_collection # noqa: E501 + + This operation creates a Pinecone collection. # 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_collection_with_http_info(create_collection_request, async_req=True) + >>> result = thread.get() + + :param create_collection_request: + :type create_collection_request: CreateCollectionRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["create_collection_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_collection" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["create_collection_request"] is not None: + _body_params = _params["create_collection_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "201": "str", + "400": None, + "409": None, + "500": None, + } + + return self.api_client.call_api( + "/collections", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def create_index(self, create_request: Optional[CreateRequest] = None, **kwargs) -> IndexMeta: # noqa: E501 + """create_index # noqa: E501 + + This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # 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(create_request, async_req=True) + >>> result = thread.get() + + :param create_request: + :type create_request: CreateRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: IndexMeta + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the create_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.create_index_with_http_info(create_request, **kwargs) # noqa: E501 + + @validate_arguments + def create_index_with_http_info( + self, create_request: Optional[CreateRequest] = None, **kwargs + ) -> ApiResponse: # noqa: E501 + """create_index # noqa: E501 + + This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # 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_with_http_info(create_request, async_req=True) + >>> result = thread.get() + + :param create_request: + :type create_request: CreateRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["create_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_index" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["create_request"] is not None: + _body_params = _params["create_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "201": "IndexMeta", + "400": None, + "409": None, + "500": None, + } + + return self.api_client.call_api( + "/databases", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def delete_collection( + self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs + ) -> str: # noqa: E501 + """delete_collection # noqa: E501 + + This operation deletes an existing collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_collection(collection_name, async_req=True) + >>> result = thread.get() + + :param collection_name: The name of the collection (required) + :type collection_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the delete_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.delete_collection_with_http_info(collection_name, **kwargs) # noqa: E501 + + @validate_arguments + def delete_collection_with_http_info( + self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs + ) -> ApiResponse: # noqa: E501 + """delete_collection # noqa: E501 + + This operation deletes an existing collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_collection_with_http_info(collection_name, async_req=True) + >>> result = thread.get() + + :param collection_name: The name of the collection (required) + :type collection_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["collection_name"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete_collection" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params["collection_name"]: + _path_params["collectionName"] = _params["collection_name"] + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "202": "str", + "404": None, + "500": None, + } + + return self.api_client.call_api( + "/collections/{collectionName}", + "DELETE", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def delete_index( + self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs + ) -> str: # noqa: E501 + """delete_index # noqa: E501 + + This operation deletes an existing index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_index(index_name, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the delete_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.delete_index_with_http_info(index_name, **kwargs) # noqa: E501 + + @validate_arguments + def delete_index_with_http_info( + self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs + ) -> ApiResponse: # noqa: E501 + """delete_index # noqa: E501 + + This operation deletes an existing index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_index_with_http_info(index_name, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["index_name"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete_index" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params["index_name"]: + _path_params["indexName"] = _params["index_name"] + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "202": "str", + "404": None, + "500": None, + } + + return self.api_client.call_api( + "/databases/{indexName}", + "DELETE", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __create_collection(self, **kwargs): - """create_collection # noqa: E501 - - This operation creates a Pinecone collection from an existing index. # 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_collection(async_req=True) - >>> result = thread.get() - - - Keyword Args: - create_collection_request (CreateCollectionRequest): [optional] - _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: - str - 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") - return self.call_with_http_info(**kwargs) - - self.create_collection = _Endpoint( - settings={ - "response_type": (str,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "create_collection", - "http_method": "POST", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "create_collection_request", - ], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "create_collection_request": (CreateCollectionRequest,), - }, - "attribute_map": {}, - "location_map": { - "create_collection_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["text/plain"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_collection, + @validate_arguments + def describe_collection( + self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs + ) -> CollectionMeta: # noqa: E501 + """describe_collection # noqa: E501 + + Get a description of a collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_collection(collection_name, async_req=True) + >>> result = thread.get() + + :param collection_name: The name of the collection (required) + :type collection_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: CollectionMeta + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the describe_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.describe_collection_with_http_info(collection_name, **kwargs) # noqa: E501 + + @validate_arguments + def describe_collection_with_http_info( + self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs + ) -> ApiResponse: # noqa: E501 + """describe_collection # noqa: E501 + + Get a description of a collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_collection_with_http_info(collection_name, async_req=True) + >>> result = thread.get() + + :param collection_name: The name of the collection (required) + :type collection_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(CollectionMeta, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["collection_name"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __create_index(self, **kwargs): - """create_index # noqa: E501 - - This operation creates a Pinecone index. Specify the distance metric, the dimension of vectors to be stored in the index, the numbers replicas to use, and the collection from which to create the index, if applicable. # 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(async_req=True) - >>> result = thread.get() - - - Keyword Args: - create_request (CreateRequest): [optional] - _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: - str - 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") - return self.call_with_http_info(**kwargs) - - self.create_index = _Endpoint( - settings={ - "response_type": (str,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/databases", - "operation_id": "create_index", - "http_method": "POST", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "create_request", - ], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "create_request": (CreateRequest,), - }, - "attribute_map": {}, - "location_map": { - "create_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["text/plain"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_index, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_collection" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params["collection_name"]: + _path_params["collectionName"] = _params["collection_name"] + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "CollectionMeta", + "404": None, + "500": None, + } + + return self.api_client.call_api( + "/collections/{collectionName}", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __delete_collection(self, collection_name, **kwargs): - """delete_collection # noqa: E501 - - This operation deletes an existing collection. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_collection(collection_name, async_req=True) - >>> result = thread.get() - - Args: - collection_name (str): The name of the collection - - 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: - str - 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["collection_name"] = collection_name - return self.call_with_http_info(**kwargs) - - self.delete_collection = _Endpoint( - settings={ - "response_type": (str,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collectionName}", - "operation_id": "delete_collection", - "http_method": "DELETE", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "collection_name", - ], - "required": [ - "collection_name", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "collection_name": (str,), - }, - "attribute_map": { - "collection_name": "collectionName", - }, - "location_map": { - "collection_name": "path", - }, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["text/plain"], - "content_type": [], - }, - api_client=api_client, - callable=__delete_collection, + @validate_arguments + def describe_index( + self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs + ) -> IndexMeta: # noqa: E501 + """describe_index # noqa: E501 + + Get a description of an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index(index_name, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: IndexMeta + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the describe_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.describe_index_with_http_info(index_name, **kwargs) # noqa: E501 + + @validate_arguments + def describe_index_with_http_info( + self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs + ) -> ApiResponse: # noqa: E501 + """describe_index # noqa: E501 + + Get a description of an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_with_http_info(index_name, async_req=True) + >>> result = thread.get() + + :param index_name: The name of the index (required) + :type index_name: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = ["index_name"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __delete_index(self, index_name, **kwargs): - """delete_index # noqa: E501 - - This operation deletes an existing index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_index(index_name, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index - - 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: - str - 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["index_name"] = index_name - return self.call_with_http_info(**kwargs) - - self.delete_index = _Endpoint( - settings={ - "response_type": (str,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/databases/{indexName}", - "operation_id": "delete_index", - "http_method": "DELETE", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "index_name", - ], - "required": [ - "index_name", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "index_name": (str,), - }, - "attribute_map": { - "index_name": "indexName", - }, - "location_map": { - "index_name": "path", - }, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["text/plain"], - "content_type": [], - }, - api_client=api_client, - callable=__delete_index, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params["index_name"]: + _path_params["indexName"] = _params["index_name"] + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "IndexMeta", + "404": None, + "500": None, + } + + return self.api_client.call_api( + "/databases/{indexName}", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __describe_collection(self, collection_name, **kwargs): - """describe_collection # noqa: E501 - - Get a description of a collection, including the name, size, and status. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_collection(collection_name, async_req=True) - >>> result = thread.get() - - Args: - collection_name (str): The name of the collection - - 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: - CollectionMeta - 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["collection_name"] = collection_name - return self.call_with_http_info(**kwargs) - - self.describe_collection = _Endpoint( - settings={ - "response_type": (CollectionMeta,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collectionName}", - "operation_id": "describe_collection", - "http_method": "GET", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "collection_name", - ], - "required": [ - "collection_name", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "collection_name": (str,), - }, - "attribute_map": { - "collection_name": "collectionName", - }, - "location_map": { - "collection_name": "path", - }, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["application/json"], - "content_type": [], - }, - api_client=api_client, - callable=__describe_collection, + @validate_arguments + def list_collections(self, **kwargs) -> List[str]: # noqa: E501 + """list_collections # noqa: E501 + + This operation returns a list of your Pinecone collections. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_collections(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: List[str] + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the list_collections_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.list_collections_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def list_collections_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """list_collections # noqa: E501 + + This operation returns a list of your Pinecone collections. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_collections_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(List[str], status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = [] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __describe_index(self, index_name, **kwargs): - """describe_index # noqa: E501 - - Get a description of an index, including dimension, distance metric, number of replicas, and more. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index(index_name, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index - - 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: - IndexMeta - 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["index_name"] = index_name - return self.call_with_http_info(**kwargs) - - self.describe_index = _Endpoint( - settings={ - "response_type": (IndexMeta,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/databases/{indexName}", - "operation_id": "describe_index", - "http_method": "GET", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={ - "all": [ - "index_name", - ], - "required": [ - "index_name", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "index_name": (str,), - }, - "attribute_map": { - "index_name": "indexName", - }, - "location_map": { - "index_name": "path", - }, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["application/json"], - "content_type": [], - }, - api_client=api_client, - callable=__describe_index, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method list_collections" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json; charset=utf-8"] + ) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "List[str]", + } + + return self.api_client.call_api( + "/collections", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __list_collections(self, **kwargs): - """list_collections # noqa: E501 - - This operation returns a list of your Pinecone collections. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_collections(async_req=True) - >>> result = thread.get() - - - 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: - [str] - 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") - return self.call_with_http_info(**kwargs) - - self.list_collections = _Endpoint( - settings={ - "response_type": ([str],), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "list_collections", - "http_method": "GET", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={"all": [], "required": [], "nullable": [], "enum": [], "validation": []}, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {}, - "attribute_map": {}, - "location_map": {}, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["application/json; charset=utf-8"], - "content_type": [], - }, - api_client=api_client, - callable=__list_collections, + @validate_arguments + def list_indexes(self, **kwargs) -> ListIndexes200Response: # noqa: E501 + """list_indexes # noqa: E501 + + This operation returns a list of your Pinecone indexes. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_indexes(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ListIndexes200Response + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the list_indexes_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.list_indexes_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def list_indexes_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """list_indexes # noqa: E501 + + This operation returns a list of your Pinecone indexes. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_indexes_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ListIndexes200Response, status_code(int), headers(HTTPHeaderDict)) + """ + + _hosts = ["https://controller.{environment}.pinecone.io"] + _host = _hosts[0] + if kwargs.get("_host_index"): + _host_index = int(kwargs.get("_host_index")) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) + _host = _hosts[_host_index] + _params = locals() + + _all_params = [] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __list_indexes(self, **kwargs): - """list_indexes # noqa: E501 - - This operation returns a list of the indexes in the current project. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_indexes(async_req=True) - >>> result = thread.get() - - - 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: - [str] - 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") - return self.call_with_http_info(**kwargs) - - self.list_indexes = _Endpoint( - settings={ - "response_type": ([str],), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/databases", - "operation_id": "list_indexes", - "http_method": "GET", - "servers": [ - { - "url": "https://controller.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "environment": { - "description": "No description provided", - "default_value": "unknown", - } - }, - }, - ], - }, - params_map={"all": [], "required": [], "nullable": [], "enum": [], "validation": []}, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {}, - "attribute_map": {}, - "location_map": {}, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["application/json; charset=utf-8"], - "content_type": [], - }, - api_client=api_client, - callable=__list_indexes, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params and _key != "_host_index": + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method list_indexes" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json; charset=utf-8"] + ) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "ListIndexes200Response", + } + + return self.api_client.call_api( + "/databases", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + _host=_host, + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) diff --git a/pinecone/core/client/api/vector_operations_api.py b/pinecone/core/client/api/vector_operations_api.py index 1f6d2d259..98c1d1a6d 100644 --- a/pinecone/core/client/api/vector_operations_api.py +++ b/pinecone/core/client/api/vector_operations_api.py @@ -1,746 +1,1233 @@ +# coding: utf-8 + """ - Pinecone vector operations API + Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.client.model_utils import ( # noqa: F401 - check_allowed_values, - check_validations, - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.client.model.delete_request import DeleteRequest -from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.model.fetch_response import FetchResponse -from pinecone.core.client.model.query_request import QueryRequest -from pinecone.core.client.model.query_response import QueryResponse -from pinecone.core.client.model.rpc_status import RpcStatus -from pinecone.core.client.model.update_request import UpdateRequest -from pinecone.core.client.model.upsert_request import UpsertRequest -from pinecone.core.client.model.upsert_response import UpsertResponse - - -class VectorOperationsApi(object): +import io +import warnings + +from pydantic import validate_arguments, ValidationError + +from typing_extensions import Annotated +from pydantic import Field, StrictBool, StrictStr, conlist + +from typing import Any, Dict, Optional + +from pinecone.core.client.models.delete_request import DeleteRequest +from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.models.fetch_response import FetchResponse +from pinecone.core.client.models.query_request import QueryRequest +from pinecone.core.client.models.query_response import QueryResponse +from pinecone.core.client.models.update_request import UpdateRequest +from pinecone.core.client.models.upsert_request import UpsertRequest +from pinecone.core.client.models.upsert_response import UpsertResponse + +from pinecone.core.client.api_client import ApiClient +from pinecone.core.client.api_response import ApiResponse +from pinecone.core.client.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class VectorOperationsApi: """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def __delete(self, delete_request, **kwargs): - """Delete # noqa: E501 - - The `Delete` operation deletes records by ID from a single namespace. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.delete(delete_request, async_req=True) - >>> result = thread.get() - - Args: - delete_request (DeleteRequest): - - Keyword Args: - _return_http_data_only (bool): Return response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, date, datetime, dict, float, int, list, str, none_type)} - 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["delete_request"] = delete_request - return self.call_with_http_info(**kwargs) - - self.delete = _Endpoint( - settings={ - "response_type": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/delete", - "operation_id": "delete", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": [ - "delete_request", - ], - "required": [ - "delete_request", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "delete_request": (DeleteRequest,), - }, - "attribute_map": {}, - "location_map": { - "delete_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__delete, + @validate_arguments + def delete(self, delete_request: DeleteRequest, **kwargs) -> object: # noqa: E501 + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete(delete_request, async_req=True) + >>> result = thread.get() + + :param delete_request: (required) + :type delete_request: DeleteRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: object + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the delete_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.delete_with_http_info(delete_request, **kwargs) # noqa: E501 + + @validate_arguments + def delete_with_http_info(self, delete_request: DeleteRequest, **kwargs) -> ApiResponse: # noqa: E501 + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete_with_http_info(delete_request, async_req=True) + >>> result = thread.get() + + :param delete_request: (required) + :type delete_request: DeleteRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["delete_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["delete_request"] is not None: + _body_params = _params["delete_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "object", + } + + return self.api_client.call_api( + "/vectors/delete", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def delete1( + self, + ids: Annotated[Optional[conlist(StrictStr)], Field(description="Vectors to delete.")] = None, + delete_all: Annotated[ + Optional[StrictBool], + Field(description="This indicates that all vectors in the index namespace should be deleted."), + ] = None, + namespace: Annotated[ + Optional[StrictStr], Field(description="The namespace to delete vectors from, if applicable.") + ] = None, + **kwargs, + ) -> object: # noqa: E501 + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete1(ids, delete_all, namespace, async_req=True) + >>> result = thread.get() + + :param ids: Vectors to delete. + :type ids: List[str] + :param delete_all: This indicates that all vectors in the index namespace should be deleted. + :type delete_all: bool + :param namespace: The namespace to delete vectors from, if applicable. + :type namespace: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: object + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the delete1_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.delete1_with_http_info(ids, delete_all, namespace, **kwargs) # noqa: E501 + + @validate_arguments + def delete1_with_http_info( + self, + ids: Annotated[Optional[conlist(StrictStr)], Field(description="Vectors to delete.")] = None, + delete_all: Annotated[ + Optional[StrictBool], + Field(description="This indicates that all vectors in the index namespace should be deleted."), + ] = None, + namespace: Annotated[ + Optional[StrictStr], Field(description="The namespace to delete vectors from, if applicable.") + ] = None, + **kwargs, + ) -> ApiResponse: # noqa: E501 + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete1_with_http_info(ids, delete_all, namespace, async_req=True) + >>> result = thread.get() + + :param ids: Vectors to delete. + :type ids: List[str] + :param delete_all: This indicates that all vectors in the index namespace should be deleted. + :type delete_all: bool + :param namespace: The namespace to delete vectors from, if applicable. + :type namespace: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["ids", "delete_all", "namespace"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __delete1(self, **kwargs): - """Delete # noqa: E501 - - The `Delete` operation deletes records by ID from a single namespace. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.delete1(async_req=True) - >>> result = thread.get() - - - Keyword Args: - ids ([str]): Vectors to delete. [optional] - delete_all (bool): This indicates that all records in the index namespace should be deleted. [optional] Default is False. - namespace (str): The namespace to delete records from, if applicable. [optional] - _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 - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): Timeout setting for this request. If - one number is provided, this number is the total request timeout. This argument can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): Specifies if type checking - should be done after the data is sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done after the data is received from the server. - Default is True. - _host_index (int/None): Specifies the index of the server - to use. - Default is to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, date, datetime, dict, float, int, list, str, none_type)} - 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") - return self.call_with_http_info(**kwargs) - - self.delete1 = _Endpoint( - settings={ - "response_type": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/delete", - "operation_id": "delete1", - "http_method": "DELETE", - "servers": None, - }, - params_map={ - "all": [ - "ids", - "delete_all", - "namespace", - ], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "ids": ([str],), - "delete_all": (bool,), - "namespace": (str,), - }, - "attribute_map": { - "ids": "ids", - "delete_all": "deleteAll", - "namespace": "namespace", - }, - "location_map": { - "ids": "query", - "delete_all": "query", - "namespace": "query", - }, - "collection_format_map": { - "ids": "multi", - }, - }, - headers_map={ - "accept": ["application/json"], - "content_type": [], - }, - api_client=api_client, - callable=__delete1, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete1" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + if _params.get("ids") is not None: # noqa: E501 + _query_params.append(("ids", _params["ids"])) + _collection_formats["ids"] = "multi" + + if _params.get("delete_all") is not None: # noqa: E501 + _query_params.append(("deleteAll", _params["delete_all"])) + + if _params.get("namespace") is not None: # noqa: E501 + _query_params.append(("namespace", _params["namespace"])) + + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "object", + } + + return self.api_client.call_api( + "/vectors/delete", + "DELETE", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __describe_index_stats(self, describe_index_stats_request, **kwargs): - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.describe_index_stats(describe_index_stats_request, async_req=True) - >>> result = thread.get() - - Args: - describe_index_stats_request (DescribeIndexStatsRequest): - - Keyword Args: - _return_http_data_only (bool): Return head status - code or headers. Default is True. - _preload_content (bool): If False, the urllib3.HTTPResponse object - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - DescribeIndexStatsResponse - 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["describe_index_stats_request"] = describe_index_stats_request - return self.call_with_http_info(**kwargs) - - self.describe_index_stats = _Endpoint( - settings={ - "response_type": (DescribeIndexStatsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/describe_index_stats", - "operation_id": "describe_index_stats", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": [ - "describe_index_stats_request", - ], - "required": [ - "describe_index_stats_request", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "describe_index_stats_request": (DescribeIndexStatsRequest,), - }, - "attribute_map": {}, - "location_map": { - "describe_index_stats_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__describe_index_stats, + @validate_arguments + def describe_index_stats( + self, describe_index_stats_request: DescribeIndexStatsRequest, **kwargs + ) -> DescribeIndexStatsResponse: # noqa: E501 + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats(describe_index_stats_request, async_req=True) + >>> result = thread.get() + + :param describe_index_stats_request: (required) + :type describe_index_stats_request: DescribeIndexStatsRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: DescribeIndexStatsResponse + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the describe_index_stats_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.describe_index_stats_with_http_info(describe_index_stats_request, **kwargs) # noqa: E501 + + @validate_arguments + def describe_index_stats_with_http_info( + self, describe_index_stats_request: DescribeIndexStatsRequest, **kwargs + ) -> ApiResponse: # noqa: E501 + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats_with_http_info(describe_index_stats_request, async_req=True) + >>> result = thread.get() + + :param describe_index_stats_request: (required) + :type describe_index_stats_request: DescribeIndexStatsRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(DescribeIndexStatsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["describe_index_stats_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __describe_index_stats1(self, **kwargs): - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.describe_index_stats1(async_req=True) - >>> result = thread.get() - - - 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 - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - DescribeIndexStatsResponse - 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") - return self.call_with_http_info(**kwargs) - - self.describe_index_stats1 = _Endpoint( - settings={ - "response_type": (DescribeIndexStatsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/describe_index_stats", - "operation_id": "describe_index_stats1", - "http_method": "GET", - "servers": None, - }, - params_map={"all": [], "required": [], "nullable": [], "enum": [], "validation": []}, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {}, - "attribute_map": {}, - "location_map": {}, - "collection_format_map": {}, - }, - headers_map={ - "accept": ["application/json"], - "content_type": [], - }, - api_client=api_client, - callable=__describe_index_stats1, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index_stats" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["describe_index_stats_request"] is not None: + _body_params = _params["describe_index_stats_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "DescribeIndexStatsResponse", + } + + return self.api_client.call_api( + "/describe_index_stats", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def describe_index_stats1(self, **kwargs) -> DescribeIndexStatsResponse: # noqa: E501 + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats1(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: DescribeIndexStatsResponse + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the describe_index_stats1_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.describe_index_stats1_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def describe_index_stats1_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats1_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(DescribeIndexStatsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index_stats1" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "DescribeIndexStatsResponse", + } + + return self.api_client.call_api( + "/describe_index_stats", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def fetch( + self, + ids: Annotated[ + conlist(StrictStr), + Field(..., description="The vector IDs to fetch. Does not accept values containing spaces."), + ], + namespace: Optional[StrictStr] = None, + **kwargs, + ) -> FetchResponse: # noqa: E501 + """Fetch # noqa: E501 + + The `Fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.fetch(ids, namespace, async_req=True) + >>> result = thread.get() + + :param ids: The vector IDs to fetch. Does not accept values containing spaces. (required) + :type ids: List[str] + :param namespace: + :type namespace: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: FetchResponse + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the fetch_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.fetch_with_http_info(ids, namespace, **kwargs) # noqa: E501 + + @validate_arguments + def fetch_with_http_info( + self, + ids: Annotated[ + conlist(StrictStr), + Field(..., description="The vector IDs to fetch. Does not accept values containing spaces."), + ], + namespace: Optional[StrictStr] = None, + **kwargs, + ) -> ApiResponse: # noqa: E501 + """Fetch # noqa: E501 + + The `Fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.fetch_with_http_info(ids, namespace, async_req=True) + >>> result = thread.get() + + :param ids: The vector IDs to fetch. Does not accept values containing spaces. (required) + :type ids: List[str] + :param namespace: + :type namespace: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(FetchResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["ids", "namespace"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method fetch" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + if _params.get("ids") is not None: # noqa: E501 + _query_params.append(("ids", _params["ids"])) + _collection_formats["ids"] = "multi" + + if _params.get("namespace") is not None: # noqa: E501 + _query_params.append(("namespace", _params["namespace"])) + + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "FetchResponse", + } + + return self.api_client.call_api( + "/vectors/fetch", + "GET", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), + ) + + @validate_arguments + def query(self, query_request: QueryRequest, **kwargs) -> QueryResponse: # noqa: E501 + """Query # noqa: E501 + + 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.query(query_request, async_req=True) + >>> result = thread.get() + + :param query_request: (required) + :type query_request: QueryRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: QueryResponse + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the query_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.query_with_http_info(query_request, **kwargs) # noqa: E501 + + @validate_arguments + def query_with_http_info(self, query_request: QueryRequest, **kwargs) -> ApiResponse: # noqa: E501 + """Query # noqa: E501 + + 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.query_with_http_info(query_request, async_req=True) + >>> result = thread.get() + + :param query_request: (required) + :type query_request: QueryRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(QueryResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["query_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] + ) + + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method query" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["query_request"] is not None: + _body_params = _params["query_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "QueryResponse", + } + + return self.api_client.call_api( + "/query", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __fetch(self, ids, **kwargs): - """Fetch # noqa: E501 - - The `Fetch` operation looks up and returns vectors by ID from a single namespace. The returned vectors include the vector data and metadata. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.fetch(ids, async_req=True) - >>> result = thread.get() - - Args: - ids ([str]): The vector IDs to fetch. Does not accept values containing spaces. - - Keyword Args: - namespace (str): [optional] - _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 - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - FetchResponse - 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["ids"] = ids - return self.call_with_http_info(**kwargs) - - self.fetch = _Endpoint( - settings={ - "response_type": (FetchResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/fetch", - "operation_id": "fetch", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": [ - "ids", - "namespace", - ], - "required": [ - "ids", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "ids": ([str],), - "namespace": (str,), - }, - "attribute_map": { - "ids": "ids", - "namespace": "namespace", - }, - "location_map": { - "ids": "query", - "namespace": "query", - }, - "collection_format_map": { - "ids": "multi", - }, - }, - headers_map={ - "accept": ["application/json"], - "content_type": [], - }, - api_client=api_client, - callable=__fetch, + @validate_arguments + def update(self, update_request: UpdateRequest, **kwargs) -> object: # noqa: E501 + """Update # noqa: E501 + + The `Update` operation updates 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update(update_request, async_req=True) + >>> result = thread.get() + + :param update_request: (required) + :type update_request: UpdateRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: object + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the update_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.update_with_http_info(update_request, **kwargs) # noqa: E501 + + @validate_arguments + def update_with_http_info(self, update_request: UpdateRequest, **kwargs) -> ApiResponse: # noqa: E501 + """Update # noqa: E501 + + The `Update` operation updates 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update_with_http_info(update_request, async_req=True) + >>> result = thread.get() + + :param update_request: (required) + :type update_request: UpdateRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["update_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __query(self, query_request, **kwargs): - """Query # noqa: E501 - - The `Query` operation searches a namespace using a query vector. It retrieves the IDs of the most similar records in a namespace along with their similarity scores. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.query(query_request, async_req=True) - >>> result = thread.get() - - Args: - query_request (QueryRequest): - - Keyword Args: - _return_http_data_only (bool): Return response data without head status - code and headers. Default is True. - _preload_content (bool): If False, the urllib3.HTTPResponse object - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - QueryResponse - 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["query_request"] = query_request - return self.call_with_http_info(**kwargs) - - self.query = _Endpoint( - settings={ - "response_type": (QueryResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/query", - "operation_id": "query", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": [ - "query_request", - ], - "required": [ - "query_request", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "query_request": (QueryRequest,), - }, - "attribute_map": {}, - "location_map": { - "query_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__query, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method update" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["update_request"] is not None: + _body_params = _params["update_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "object", + } + + return self.api_client.call_api( + "/vectors/update", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) - def __update(self, update_request, **kwargs): - """Update # noqa: E501 - - The `Update` operation updates a vector in a namespace. If a value is included, it overwrites the previous value. If set_metadata is included, the values of the fields specified in it are added to or overwrite the previous values. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.update(update_request, async_req=True) - >>> result = thread.get() - - Args: - update_request (UpdateRequest): - - Keyword Args: - _return_http_data_only (bool): Response head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, date, datetime, dict, float, int, list, str, none_type)} - 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["update_request"] = update_request - return self.call_with_http_info(**kwargs) - - self.update = _Endpoint( - settings={ - "response_type": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/update", - "operation_id": "update", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": [ - "update_request", - ], - "required": [ - "update_request", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "update_request": (UpdateRequest,), - }, - "attribute_map": {}, - "location_map": { - "update_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__update, + @validate_arguments + def upsert(self, upsert_request: UpsertRequest, **kwargs) -> UpsertResponse: # noqa: E501 + """Upsert # noqa: E501 + + 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. # 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(upsert_request, async_req=True) + >>> result = thread.get() + + :param upsert_request: (required) + :type upsert_request: UpsertRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: 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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: UpsertResponse + """ + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + message = "Error! Please call the upsert_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.upsert_with_http_info(upsert_request, **kwargs) # noqa: E501 + + @validate_arguments + def upsert_with_http_info(self, upsert_request: UpsertRequest, **kwargs) -> ApiResponse: # noqa: E501 + """Upsert # noqa: E501 + + 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. # 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_with_http_info(upsert_request, async_req=True) + >>> result = thread.get() + + :param upsert_request: (required) + :type upsert_request: UpsertRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: 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. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(UpsertResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = ["upsert_request"] + _all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", + ] ) - def __upsert(self, upsert_request, **kwargs): - """Upsert # noqa: E501 - - The `Upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it overwrites the previous value. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, pass async_req=True - - >>> thread = api.upsert(upsert_request, async_req=True) - >>> result = thread.get() - - Args: - upsert_request (UpsertRequest): - - Keyword Args: - _return_http_data_only (bool): Return response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - is returned without reading or decoding response data. - Default is True. - _request_timeout (int/float/tuple): The timeout setting for this request. If - one number is provided, it is the 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 on the data sent to the server. - Default is True. - _check_return_type (bool): Specifies if type checking - should be done on 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 to read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - UpsertResponse - 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["upsert_request"] = upsert_request - return self.call_with_http_info(**kwargs) - - self.upsert = _Endpoint( - settings={ - "response_type": (UpsertResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/upsert", - "operation_id": "upsert", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": [ - "upsert_request", - ], - "required": [ - "upsert_request", - ], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "upsert_request": (UpsertRequest,), - }, - "attribute_map": {}, - "location_map": { - "upsert_request": "body", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__upsert, + # validate the arguments + for _key, _val in _params["kwargs"].items(): + if _key not in _all_params: + raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method upsert" % _key) + _params[_key] = _val + del _params["kwargs"] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get("_headers", {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params["upsert_request"] is not None: + _body_params = _params["upsert_request"] + + # set the HTTP header `Accept` + _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get( + "_content_type", self.api_client.select_header_content_type(["application/json"]) + ) + if _content_types_list: + _header_params["Content-Type"] = _content_types_list + + # authentication setting + _auth_settings = ["ApiKeyAuth"] # noqa: E501 + + _response_types_map = { + "200": "UpsertResponse", + } + + return self.api_client.call_api( + "/vectors/upsert", + "POST", + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), + collection_formats=_collection_formats, + _request_auth=_params.get("_request_auth"), ) diff --git a/pinecone/core/client/api_client.py b/pinecone/core/client/api_client.py index 8084c5321..3c5bf896d 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/client/api_client.py @@ -1,46 +1,38 @@ +# coding: utf-8 + """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -import json import atexit +import datetime +from dateutil.parser import parse +import json import mimetypes from multiprocessing.pool import ThreadPool -import io import os import re -import typing -from urllib.parse import quote -from urllib3.fields import RequestField +import tempfile +from urllib.parse import quote -from pinecone.core.client import rest from pinecone.core.client.configuration import Configuration -from pinecone.core.client.exceptions import ApiTypeError, ApiValueError, ApiException -from pinecone.core.client.model_utils import ( - ModelNormal, - ModelSimple, - ModelComposed, - check_allowed_values, - check_validations, - date, - datetime, - deserialize_file, - file_type, - model_to_dict, - none_type, - validate_and_convert_types, -) - - -class ApiClient(object): +from pinecone.core.client.api_response import ApiResponse +import pinecone.core.client.models +from pinecone.core.client import rest +from pinecone.core.client.exceptions import ApiValueError, ApiException + + +class ApiClient: """Generic API client for OpenAPI client library builds. OpenAPI generic API client. This client handles the client- @@ -48,10 +40,6 @@ class ApiClient(object): the methods and models for each application are generated from the OpenAPI templates. - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to @@ -62,11 +50,23 @@ class ApiClient(object): to the API. More threads means more concurrent API requests. """ + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + "int": int, + "long": int, # TODO remove as only py3 is supported? + "float": float, + "str": str, + "bool": bool, + "date": datetime.date, + "datetime": datetime.datetime, + "object": object, + } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1): + def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> None: + # use default configuration if none is provided if configuration is None: - configuration = Configuration.get_default_copy() + configuration = Configuration.get_default() self.configuration = configuration self.pool_threads = pool_threads @@ -77,6 +77,7 @@ def __init__(self, configuration=None, header_name=None, header_value=None, cook self.cookie = cookie # Set default User-Agent. self.user_agent = "OpenAPI-Generator/1.0.0/python" + self.client_side_validation = configuration.client_side_validation def __enter__(self): return self @@ -114,24 +115,50 @@ def user_agent(self, value): def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + def __call_api( self, - resource_path: str, - method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_types_map=None, + auth_settings=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + _request_auth=None, ): config = self.configuration @@ -152,27 +179,22 @@ def __call_api( # specified safe chars, encode everything resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)) - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, collection_formats) - # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) post_params = self.parameters_to_tuples(post_params, collection_formats) post_params.extend(self.files_parameters(files)) - if header_params["Content-Type"].startswith("multipart"): - post_params = self.parameters_to_multipart(post_params, (dict)) + + # auth setting + self.update_params_for_auth( + header_params, query_params, auth_settings, resource_path, method, body, request_auth=_request_auth + ) # body if body: body = self.sanitize_for_serialization(body) - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings, resource_path, method, body) - # request url if _host is None: url = self.configuration.host + resource_path @@ -180,6 +202,12 @@ def __call_api( # use server/host defined in path or operation instead url = _host + resource_path + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query(query_params, collection_formats) + url += "?" + url_query + try: # perform request and return response response_data = self.request( @@ -193,60 +221,51 @@ def __call_api( _request_timeout=_request_timeout, ) except ApiException as e: - e.body = e.body.decode("utf-8") + if e.body: + e.body = e.body.decode("utf-8") raise e self.last_response = response_data - return_data = response_data - - if not _preload_content: - return return_data - return return_data + return_data = None # assuming derialization is not needed + # data needs deserialization or returns HTTP data (deserialized) only + if _preload_content or _return_http_data_only: + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - # deserialize response data - if response_type: - if response_type != (file_type,): - encoding = "utf-8" + if response_type == "bytearray": + response_data.data = response_data.data + else: + match = None content_type = response_data.getheader("content-type") if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - if match: - encoding = match.group(1) + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" response_data.data = response_data.data.decode(encoding) - return_data = self.deserialize(response_data, response_type, _check_type) - else: - return_data = None + # deserialize response data + if response_type == "bytearray": + return_data = response_data.data + elif response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if _return_http_data_only: return return_data else: - return (return_data, response_data.status, response_data.getheaders()) + return ApiResponse( + status_code=response_data.status, + data=return_data, + headers=response_data.getheaders(), + raw_data=response_data.data, + ) - def parameters_to_multipart(self, params, collection_types): - """Get parameters as list of tuples, formatting as json if value is collection_types + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. - :param params: Parameters as list of two-tuples - :param dict collection_types: Parameter collection types - :return: Parameters as list of tuple or urllib3.fields.RequestField - """ - new_params = [] - if collection_types is None: - collection_types = dict - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json - v = json.dumps(v, ensure_ascii=False).encode("utf-8") - field = RequestField(k, v) - field.make_multipart(content_type="application/json; charset=utf-8") - new_params.append(field) - else: - new_params.append((k, v)) - return new_params - - @classmethod - def sanitize_for_serialization(cls, obj): - """Prepares data for transmission before it is sent with the rest client If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date @@ -254,84 +273,111 @@ def sanitize_for_serialization(cls, obj): If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. - If obj is io.IOBase, return the bytes + :param obj: The data to serialize. :return: The serialized form of data. """ - if isinstance(obj, (ModelNormal, ModelComposed)): - return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()} - elif isinstance(obj, io.IOBase): - return cls.get_file_data_and_close_file(obj) - elif isinstance(obj, (str, int, float, none_type, bool)): + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj - elif isinstance(obj, (datetime, date)): + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) + elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - elif isinstance(obj, ModelSimple): - return cls.sanitize_for_serialization(obj.value) - elif isinstance(obj, (list, tuple)): - return [cls.sanitize_for_serialization(item) for item in obj] + if isinstance(obj, dict): - return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} - raise ApiValueError("Unable to prepare type {} for serialization".format(obj.__class__.__name__)) + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = obj.to_dict() + + return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()} - def deserialize(self, response, response_type, _check_type): + def deserialize(self, response, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param _check_type: boolean, whether to check the types of the data - received from the server - :type _check_type: bool + :param response_type: class literal for + deserialized object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance - if response_type == (file_type,): - content_disposition = response.getheader("Content-Disposition") - return deserialize_file(response.data, self.configuration, content_disposition=content_disposition) + if response_type == "file": + return self.__deserialize_file(response) # fetch data from response object try: - received_data = json.loads(response.data) + data = json.loads(response.data) except ValueError: - received_data = response.data + data = response.data - # store our data under the key of 'received_data' so users have some - # context if they are deserializing a string and the data type is wrong - deserialized_data = validate_and_convert_types( - received_data, response_type, ["received_data"], True, _check_type, configuration=self.configuration - ) - return deserialized_data + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith("List["): + sub_kls = re.match(r"List\[(.*)]", klass).group(1) + return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + + if klass.startswith("Dict["): + sub_kls = re.match(r"Dict\[([^,]*), (.*)]", klass).group(2) + return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(pinecone.core.client.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) def call_api( self, - resource_path: str, - method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - async_req: typing.Optional[bool] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_types_map=None, + auth_settings=None, + async_req=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + _request_auth=None, ): """Makes the HTTP request (synchronous) and returns deserialized data. @@ -347,38 +393,26 @@ def call_api( :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param files: key -> field name, value -> a list of open file - objects for `multipart/form-data`. - :type files: dict + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. :param async_req bool: execute request asynchronously - :type async_req: bool, optional - :param _return_http_data_only: response data without head status code - and headers - :type _return_http_data_only: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :type collection_formats: dict, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional :param _request_timeout: 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. - :param _check_type: boolean describing if the data back from the server - should have its type checked. - :type _check_type: bool, optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_token: dict, optional :return: If async_req parameter is True, the request will be called asynchronously. @@ -396,14 +430,14 @@ def call_api( body, post_params, files, - response_type, + response_types_map, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout, _host, - _check_type, + _request_auth, ) return self.pool.apply_async( @@ -417,14 +451,14 @@ def call_api( body, post_params, files, - response_type, + response_types_map, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout, _host, - _check_type, + _request_auth, ), ) @@ -441,7 +475,7 @@ def request( ): """Makes the HTTP request using RESTClient.""" if method == "GET": - return self.rest_client.GET( + return self.rest_client.get_request( url, query_params=query_params, _preload_content=_preload_content, @@ -449,7 +483,7 @@ def request( headers=headers, ) elif method == "HEAD": - return self.rest_client.HEAD( + return self.rest_client.head_request( url, query_params=query_params, _preload_content=_preload_content, @@ -457,17 +491,15 @@ def request( headers=headers, ) elif method == "OPTIONS": - return self.rest_client.OPTIONS( + return self.rest_client.options_request( url, query_params=query_params, headers=headers, - post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, - body=body, ) elif method == "POST": - return self.rest_client.POST( + return self.rest_client.post_request( url, query_params=query_params, headers=headers, @@ -477,7 +509,7 @@ def request( body=body, ) elif method == "PUT": - return self.rest_client.PUT( + return self.rest_client.put_request( url, query_params=query_params, headers=headers, @@ -487,7 +519,7 @@ def request( body=body, ) elif method == "PATCH": - return self.rest_client.PATCH( + return self.rest_client.patch_request( url, query_params=query_params, headers=headers, @@ -497,7 +529,7 @@ def request( body=body, ) elif method == "DELETE": - return self.rest_client.DELETE( + return self.rest_client.delete_request( url, query_params=query_params, headers=headers, @@ -537,39 +569,62 @@ def parameters_to_tuples(self, params, collection_formats): new_params.append((k, v)) return new_params - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. - def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None): + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == "multi": + new_params.extend((k, value) for value in v) + else: + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" + else: # csv is the default + delimiter = "," + new_params.append((k, delimiter.join(quote(str(value)) for value in v))) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(item) for item in new_params]) + + def files_parameters(self, files=None): """Builds form parameters. - :param files: None or a dict with key=param_name and - value is a list of open file objects - :return: List of tuples of form parameters with file data + :param files: File parameters. + :return: Form parameters with files. """ - if files is None: - return [] - params = [] - for param_name, file_instances in files.items(): - if file_instances is None: - # if the file field is nullable, skip None values - continue - for file_instance in file_instances: - if file_instance is None: - # if the file field is nullable, skip None values + + if files: + for k, v in files.items(): + if not v: continue - if file_instance.closed is True: - raise ApiValueError( - "Cannot read a closed file. The passed in file_type " "for %s must be open." % param_name - ) - filename = os.path.basename(file_instance.name) - filedata = self.get_file_data_and_close_file(file_instance) - mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" - params.append(tuple([param_name, tuple([filename, filedata, mimetype])])) + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, "rb") as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" + params.append(tuple([k, tuple([filename, filedata, mimetype])])) return params @@ -582,12 +637,11 @@ def select_header_accept(self, accepts): if not accepts: return - accepts = [x.lower() for x in accepts] + for accept in accepts: + if re.search("json", accept, re.IGNORECASE): + return accept - if "application/json" in accepts: - return "application/json" - else: - return ", ".join(accepts) + return accepts[0] def select_header_content_type(self, content_types): """Returns `Content-Type` based on an array of content_types provided. @@ -596,247 +650,139 @@ def select_header_content_type(self, content_types): :return: Content-Type (e.g. application/json). """ if not content_types: - return "application/json" + return None - content_types = [x.lower() for x in content_types] + for content_type in content_types: + if re.search("json", content_type, re.IGNORECASE): + return content_type - if "application/json" in content_types or "*/*" in content_types: - return "application/json" - else: - return content_types[0] + return content_types[0] - def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body): + def update_params_for_auth(self, headers, queries, auth_settings, resource_path, method, body, request_auth=None): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. + :param queries: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. - :param resource_path: A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method. - :param body: A object representing the body of the HTTP request. - The object type is the return value of _encoder.default(). + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. """ if not auth_settings: return + if request_auth: + self._apply_auth_params(headers, queries, resource_path, method, body, request_auth) + return + for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) if auth_setting: - if auth_setting["in"] == "cookie": - headers["Cookie"] = auth_setting["value"] - elif auth_setting["in"] == "header": - if auth_setting["type"] != "http-signature": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - querys.append((auth_setting["key"], auth_setting["value"])) - else: - raise ApiValueError("Authentication token must be in `query` or `header`") - - -class Endpoint(object): - def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None): - """Creates an endpoint - - Args: - settings (dict): see below key value pairs - 'response_type' (tuple/None): response type - 'auth' (list): a list of auth type keys - 'endpoint_path' (str): the endpoint path - 'operation_id' (str): endpoint string identifier - 'http_method' (str): POST/PUT/PATCH/GET etc - 'servers' (list): list of str servers that this endpoint is at - params_map (dict): see below key value pairs - 'all' (list): list of str endpoint parameter names - 'required' (list): list of required parameter names - 'nullable' (list): list of nullable parameter names - 'enum' (list): list of parameters with enum values - 'validation' (list): list of parameters with validations - root_map - 'validations' (dict): the dict mapping endpoint parameter tuple - paths to their validation dictionaries - 'allowed_values' (dict): the dict mapping endpoint parameter - tuple paths to their allowed_values (enum) dictionaries - 'openapi_types' (dict): param_name to openapi type - 'attribute_map' (dict): param_name to camelCase name - 'location_map' (dict): param_name to 'body', 'file', 'form', - 'header', 'path', 'query' - collection_format_map (dict): param_name to `csv` etc. - headers_map (dict): see below key value pairs - 'accept' (list): list of Accept header strings - 'content_type' (list): list of Content-Type header strings - api_client (ApiClient) api client instance - callable (function): the function which is invoked when the - Endpoint is called + self._apply_auth_params(headers, queries, resource_path, method, body, auth_setting) + + def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint """ - self.settings = settings - self.params_map = params_map - self.params_map["all"].extend( - [ - "async_req", - "_host_index", - "_preload_content", - "_request_timeout", - "_return_http_data_only", - "_check_input_type", - "_check_return_type", - ] - ) - self.params_map["nullable"].extend(["_request_timeout"]) - self.validations = root_map["validations"] - self.allowed_values = root_map["allowed_values"] - self.openapi_types = root_map["openapi_types"] - extra_types = { - "async_req": (bool,), - "_host_index": (none_type, int), - "_preload_content": (bool,), - "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]), - "_return_http_data_only": (bool,), - "_check_input_type": (bool,), - "_check_return_type": (bool,), - } - self.openapi_types.update(extra_types) - self.attribute_map = root_map["attribute_map"] - self.location_map = root_map["location_map"] - self.collection_format_map = root_map["collection_format_map"] - self.headers_map = headers_map - self.api_client = api_client - self.callable = callable - - def __validate_inputs(self, kwargs): - for param in self.params_map["enum"]: - if param in kwargs: - check_allowed_values(self.allowed_values, (param,), kwargs[param]) - - for param in self.params_map["validation"]: - if param in kwargs: - check_validations( - self.validations, (param,), kwargs[param], configuration=self.api_client.configuration - ) - - if kwargs["_check_input_type"] is False: - return + if auth_setting["in"] == "cookie": + headers["Cookie"] = auth_setting["value"] + elif auth_setting["in"] == "header": + if auth_setting["type"] != "http-signature": + headers[auth_setting["key"]] = auth_setting["value"] + elif auth_setting["in"] == "query": + queries.append((auth_setting["key"], auth_setting["value"])) + else: + raise ApiValueError("Authentication token must be in `query` or `header`") - for key, value in kwargs.items(): - fixed_val = validate_and_convert_types( - value, - self.openapi_types[key], - [key], - False, - kwargs["_check_input_type"], - configuration=self.api_client.configuration, - ) - kwargs[key] = fixed_val - - def __gather_params(self, kwargs): - params = {"body": None, "collection_format": {}, "file": {}, "form": [], "header": {}, "path": {}, "query": []} - - for param_name, param_value in kwargs.items(): - param_location = self.location_map.get(param_name) - if param_location is None: - continue - if param_location: - if param_location == "body": - params["body"] = param_value - continue - base_name = self.attribute_map[param_name] - if param_location == "form" and self.openapi_types[param_name] == (file_type,): - params["file"][param_name] = [param_value] - elif param_location == "form" and self.openapi_types[param_name] == ([file_type],): - # param_value is already a list - params["file"][param_name] = param_value - elif param_location in {"form", "query"}: - param_value_full = (base_name, param_value) - params[param_location].append(param_value_full) - if param_location not in {"form", "query"}: - params[param_location][base_name] = param_value - collection_format = self.collection_format_map.get(param_name) - if collection_format: - params["collection_format"][base_name] = collection_format + def __deserialize_file(self, response): + """Deserializes body to file - return params + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) - def __call__(self, *args, **kwargs): - """This method is invoked when endpoints are called - Example: + return path - api_instance = IndexOperationsApi() - api_instance.configure_index # this is an instance of the class Endpoint - api_instance.configure_index() # this invokes api_instance.configure_index.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.configure_index.callable or self.callable in this class + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. """ - return self.callable(self, *args, **kwargs) + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data - def call_with_http_info(self, **kwargs): + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ try: - index = ( - self.api_client.configuration.server_operation_index.get( - self.settings["operation_id"], self.api_client.configuration.server_index - ) - if kwargs["_host_index"] is None - else kwargs["_host_index"] - ) - server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings["operation_id"], self.api_client.configuration.server_variables - ) - _host = self.api_client.configuration.get_host_from_settings( - index, variables=server_variables, servers=self.settings["servers"] - ) - except IndexError: - if self.settings["servers"]: - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"])) - _host = None - - for key, value in kwargs.items(): - if key not in self.params_map["all"]: - raise ApiTypeError( - "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.settings["operation_id"]) - ) - # only throw this nullable ApiValueError if _check_input_type - # is False, if _check_input_type==True we catch this case - # in self.__validate_inputs - if key not in self.params_map["nullable"] and value is None and kwargs["_check_input_type"] is False: - raise ApiValueError( - "Value may not be None for non-nullable parameter `%s`" - " when calling `%s`" % (key, self.settings["operation_id"]) - ) - - for key in self.params_map["required"]: - if key not in kwargs.keys(): - raise ApiValueError( - "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"]) - ) - - self.__validate_inputs(kwargs) - - params = self.__gather_params(kwargs) - - accept_headers_list = self.headers_map["accept"] - if accept_headers_list: - params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list) - - content_type_headers_list = self.headers_map["content_type"] - if content_type_headers_list: - header_list = self.api_client.select_header_content_type(content_type_headers_list) - params["header"]["Content-Type"] = header_list - - return self.api_client.call_api( - self.settings["endpoint_path"], - self.settings["http_method"], - params["path"], - params["query"], - params["header"], - body=params["body"], - post_params=params["form"], - files=params["file"], - response_type=self.settings["response_type"], - auth_settings=self.settings["auth"], - async_req=kwargs["async_req"], - _check_type=kwargs["_check_return_type"], - _return_http_data_only=kwargs["_return_http_data_only"], - _preload_content=kwargs["_preload_content"], - _request_timeout=kwargs["_request_timeout"], - _host=_host, - collection_formats=params["collection_format"], - ) + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string)) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string))) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/pinecone/core/client/api_response.py b/pinecone/core/client/api_response.py new file mode 100644 index 000000000..7bc03cb63 --- /dev/null +++ b/pinecone/core/client/api_response.py @@ -0,0 +1,22 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Any, Dict, Optional +from pydantic import Field, StrictInt, StrictStr + + +class ApiResponse: + """ + API response object + """ + + status_code: Optional[StrictInt] = Field(None, description="HTTP status code") + headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") + data: Optional[Any] = Field(None, description="Deserialized data given the data type") + raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + + def __init__(self, status_code=None, headers=None, data=None, raw_data=None) -> None: + self.status_code = status_code + self.headers = headers + self.data = data + self.raw_data = raw_data diff --git a/pinecone/core/client/apis/__init__.py b/pinecone/core/client/apis/__init__.py deleted file mode 100644 index 88516b08b..000000000 --- a/pinecone/core/client/apis/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# flake8: noqa - -# Import all APIs into this package. -# If you have many APIs here with many many models used in each API this may -# raise a `RecursionError`. -# In order to avoid this, import only the API that you directly need like: -# -# from .api.index_operations_api import IndexOperationsApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from pinecone.core.client.api.index_operations_api import IndexOperationsApi -from pinecone.core.client.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/client/configuration.py b/pinecone/core/client/configuration.py index 2c6baf433..7ebb57e54 100644 --- a/pinecone/core/client/configuration.py +++ b/pinecone/core/client/configuration.py @@ -1,12 +1,16 @@ +# coding: utf-8 + """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 import copy @@ -15,9 +19,7 @@ import sys import urllib3 -from http import client as http_client -from pinecone.core.client.exceptions import ApiValueError - +import http.client as httplib JSON_SCHEMA_VALIDATION_KEYWORDS = { "multipleOf", @@ -33,46 +35,20 @@ } -class Configuration(object): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. +class Configuration: + """This class contains various settings of the API client. - :param host: Base url + :param host: Base url. :param api_key: Dict to store API key(s). Each entry in the dict specifies an API key. The dict key is the name of the security scheme in the OAS specification. The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). The dict key is the name of the security scheme in the OAS specification. The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication - :param password: Password for HTTP basic authentication - :param discard_unknown_keys: Boolean value indicating whether to discard - unknown properties. A server may send a response that includes additional - properties that are not known by the client in the following scenarios: - 1. The OpenAPI document is incomplete, i.e. it does not match the server - implementation. - 2. The client was generated using an older version of the OpenAPI document - and the server has been upgraded since then. - If a schema in the OpenAPI document defines the additionalProperties attribute, - then all undeclared properties received by the server are injected into the - additional properties map. In that case, there are undeclared properties, and - nothing to discard. - :param disabled_client_side_validations (string): Comma-separated list of - JSON schema validation keywords to disable JSON schema structural validation - rules. The following keywords may be specified: multipleOf, maximum, - exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, - maxItems, minItems. - By default, the validation is performed for data generated locally by the client - and data received from the server, independent of any validation performed by - the server side. If the input data does not satisfy the JSON schema validation - rules specified in the OpenAPI document, an exception is raised. - If disabled_client_side_validations is set, structural validation is - disabled. This can be useful to troubleshoot data validation problem, such as - when the OpenAPI document validation rules do not match the actual API data - received by the server. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. :param server_index: Index to servers configuration. :param server_variables: Mapping with string values to replace variables in templated server configuration. The validation of enums is performed for @@ -81,9 +57,10 @@ class Configuration(object): configuration. :param server_operation_variables: Mapping from operation ID to a mapping with string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. + The validation of enums is performed for variables with defined enum + values before. :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format + in PEM format. :Example: @@ -114,17 +91,15 @@ def __init__( host=None, api_key=None, api_key_prefix=None, - access_token=None, username=None, password=None, - discard_unknown_keys=False, - disabled_client_side_validations="", + access_token=None, server_index=None, server_variables=None, server_operation_index=None, server_operation_variables=None, ssl_ca_cert=None, - ): + ) -> None: """Constructor""" self._base_path = "https://unknown-unknown.svc.unknown.pinecone.io" if host is None else host """Default Base url @@ -141,7 +116,6 @@ def __init__( """Temp file folder for downloading files """ # Authentication Settings - self.access_token = access_token self.api_key = {} if api_key: self.api_key = api_key @@ -161,8 +135,9 @@ def __init__( self.password = password """Password for HTTP basic authentication """ - self.discard_unknown_keys = discard_unknown_keys - self.disabled_client_side_validations = disabled_client_side_validations + self.access_token = access_token + """Access token + """ self.logger = {} """Logging Settings """ @@ -201,6 +176,10 @@ def __init__( self.assert_hostname = None """Set this to True/False to enable/disable SSL hostname verification. """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 """urllib3 connection pool's maximum number of connections saved @@ -225,8 +204,17 @@ def __init__( # Enable client side validation self.client_side_validation = True - # Options to pass down to the underlying urllib3 socket self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ def __deepcopy__(self, memo): cls = self.__class__ @@ -244,12 +232,6 @@ def __deepcopy__(self, memo): def __setattr__(self, name, value): object.__setattr__(self, name, value) - if name == "disabled_client_side_validations": - s = set(filter(None, value.split(","))) - for v in s: - if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: - raise ApiValueError("Invalid keyword: '{0}''".format(v)) - self._disabled_client_side_validations = s @classmethod def set_default(cls, default): @@ -260,21 +242,31 @@ def set_default(cls, default): :param default: object of Configuration """ - cls._default = copy.deepcopy(default) + cls._default = default @classmethod def get_default_copy(cls): - """Return new instance of configuration. + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. This method returns newly created, based on default constructor, object of Configuration class or returns a copy of default - configuration passed by the set_default method. + configuration. :return: The configuration object. """ - if cls._default is not None: - return copy.deepcopy(cls._default) - return Configuration() + if cls._default is None: + cls._default = Configuration() + return cls._default @property def logger_file(self): @@ -328,15 +320,15 @@ def debug(self, value): # if debug status is True, turn on debug logging for _, logger in self.logger.items(): logger.setLevel(logging.DEBUG) - # turn on http_client debug - http_client.HTTPConnection.debuglevel = 1 + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` for _, logger in self.logger.items(): logger.setLevel(logging.WARNING) - # turn off http_client debug - http_client.HTTPConnection.debuglevel = 0 + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): diff --git a/pinecone/core/client/exceptions.py b/pinecone/core/client/exceptions.py index 5cb822bc4..7a26ac073 100644 --- a/pinecone/core/client/exceptions.py +++ b/pinecone/core/client/exceptions.py @@ -1,23 +1,24 @@ +# coding: utf-8 + """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - + Generated by OpenAPI Generator (https://openapi-generator.tech) -from pinecone.core.exceptions import PineconeException + Do not edit the class manually. +""" # noqa: E501 -class OpenApiException(PineconeException): +class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): + def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> None: """Raises an exception for TypeErrors Args: @@ -45,7 +46,7 @@ def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None): + def __init__(self, msg, path_to_item=None) -> None: """ Args: msg (str): the exception message @@ -63,7 +64,7 @@ def __init__(self, msg, path_to_item=None): class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None): + def __init__(self, msg, path_to_item=None) -> None: """ Raised when an attribute reference or assignment fails. @@ -82,7 +83,7 @@ def __init__(self, msg, path_to_item=None): class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None): + def __init__(self, msg, path_to_item=None) -> None: """ Args: msg (str): the exception message @@ -99,7 +100,7 @@ def __init__(self, msg, path_to_item=None): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None): + def __init__(self, status=None, reason=None, http_resp=None) -> None: if http_resp: self.status = http_resp.status self.reason = http_resp.reason @@ -123,23 +124,28 @@ def __str__(self): return error_message +class BadRequestException(ApiException): + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(BadRequestException, self).__init__(status, reason, http_resp) + + class NotFoundException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): + def __init__(self, status=None, reason=None, http_resp=None) -> None: super(NotFoundException, self).__init__(status, reason, http_resp) class UnauthorizedException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): + def __init__(self, status=None, reason=None, http_resp=None) -> None: super(UnauthorizedException, self).__init__(status, reason, http_resp) class ForbiddenException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): + def __init__(self, status=None, reason=None, http_resp=None) -> None: super(ForbiddenException, self).__init__(status, reason, http_resp) class ServiceException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): + def __init__(self, status=None, reason=None, http_resp=None) -> None: super(ServiceException, self).__init__(status, reason, http_resp) diff --git a/pinecone/core/client/model/__init__.py b/pinecone/core/client/model/__init__.py deleted file mode 100644 index cfe32b784..000000000 --- a/pinecone/core/client/model/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# we can not import model classes here because that would create a circular -# reference which would not work in python2 -# do not import all models into this module because that uses a lot of memory and stack frames -# if you need the ability to import all models from one package, import them with -# from {{packageName}.models import ModelA, ModelB diff --git a/pinecone/core/client/model/approximated_config.py b/pinecone/core/client/model/approximated_config.py deleted file mode 100644 index 4c237d89e..000000000 --- a/pinecone/core/client/model/approximated_config.py +++ /dev/null @@ -1,275 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class ApproximatedConfig(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "k_bits": (int,), # noqa: E501 - "hybrid": (bool,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "k_bits": "k_bits", # noqa: E501 - "hybrid": "hybrid", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ApproximatedConfig - 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,) - k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 - hybrid (bool): [optional] if omitted the server will use the default value of False # 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 ApiTypeError( - "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 - """ApproximatedConfig - 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,) - k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 - hybrid (bool): [optional] if omitted the server will use the default value of False # 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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/collection_meta.py b/pinecone/core/client/model/collection_meta.py deleted file mode 100644 index de2f5b6b8..000000000 --- a/pinecone/core/client/model/collection_meta.py +++ /dev/null @@ -1,279 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class CollectionMeta(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "name": (str,), # noqa: E501 - "size": (int,), # noqa: E501 - "status": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "name": "name", # noqa: E501 - "size": "size", # noqa: E501 - "status": "status", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """CollectionMeta - 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,) - name (str): [optional] # noqa: E501 - size (int): The size of the collection in bytes.. [optional] # noqa: E501 - status (str): The status of the collection.. [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 ApiTypeError( - "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 - """CollectionMeta - 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,) - name (str): [optional] # noqa: E501 - size (int): The size of the collection in bytes.. [optional] # noqa: E501 - status (str): The status of the collection.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/create_collection_request.py b/pinecone/core/client/model/create_collection_request.py deleted file mode 100644 index 47379c0ea..000000000 --- a/pinecone/core/client/model/create_collection_request.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class CreateCollectionRequest(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "name": (str,), # noqa: E501 - "source": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "name": "name", # noqa: E501 - "source": "source", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, source, *args, **kwargs): # noqa: E501 - """CreateCollectionRequest - a model defined in OpenAPI - - Args: - name (str): The name of the collection to be created. - source (str): The name of the source index to be used as the source for the collection. - - 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 ApiTypeError( - "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.source = source - 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, source, *args, **kwargs): # noqa: E501 - """CreateCollectionRequest - a model defined in OpenAPI - - Args: - name (str): The name of the collection to be created. - source (str): The name of the source index to be used as the source for the collection. - - 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 ApiTypeError( - "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.source = source - 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 ApiAttributeError( - 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/client/model/create_request.py b/pinecone/core/client/model/create_request.py deleted file mode 100644 index 1aa615c0e..000000000 --- a/pinecone/core/client/model/create_request.py +++ /dev/null @@ -1,322 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class CreateRequest(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "name": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "index_type": (str,), # noqa: E501 - "metric": (str,), # noqa: E501 - "pods": (int,), # noqa: E501 - "replicas": (int,), # noqa: E501 - "shards": (int,), # noqa: E501 - "pod_type": (str,), # noqa: E501 - "index_config": (dict,), # noqa: E501 - "metadata_config": ( - {str: (bool, date, datetime, dict, float, int, list, str, none_type)}, - none_type, - ), # noqa: E501 - "source_collection": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "name": "name", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "index_type": "index_type", # noqa: E501 - "metric": "metric", # noqa: E501 - "pods": "pods", # noqa: E501 - "replicas": "replicas", # noqa: E501 - "shards": "shards", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - "index_config": "index_config", # noqa: E501 - "metadata_config": "metadata_config", # noqa: E501 - "source_collection": "source_collection", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 - """CreateRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index to be created. The maximum length is 45 characters. - dimension (int): The dimensions of the vectors to be inserted in 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,) - index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 - 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 - pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 - source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( - "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.dimension = dimension - 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, dimension, *args, **kwargs): # noqa: E501 - """CreateRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index to be created. The maximum length is 45 characters. - dimension (int): The dimensions of the vectors to be inserted in 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,) - index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 - 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 - pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 - source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( - "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.dimension = dimension - 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 ApiAttributeError( - 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/client/model/delete_request.py b/pinecone/core/client/model/delete_request.py deleted file mode 100644 index d60289048..000000000 --- a/pinecone/core/client/model/delete_request.py +++ /dev/null @@ -1,285 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class DeleteRequest(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 = { - ("ids",): {}, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "ids": ([str],), # noqa: E501 - "delete_all": (bool,), # noqa: E501 - "namespace": (str,), # noqa: E501 - "filter": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "ids": "ids", # noqa: E501 - "delete_all": "deleteAll", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "filter": "filter", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """DeleteRequest - 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,) - 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, date, datetime, 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 https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( - "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 - """DeleteRequest - 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,) - 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, date, datetime, 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 https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/describe_index_stats_request.py b/pinecone/core/client/model/describe_index_stats_request.py deleted file mode 100644 index 05c73506a..000000000 --- a/pinecone/core/client/model/describe_index_stats_request.py +++ /dev/null @@ -1,271 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class DescribeIndexStatsRequest(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "filter": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "filter": "filter", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """DescribeIndexStatsRequest - 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,) - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( - "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 - """DescribeIndexStatsRequest - 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,) - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/describe_index_stats_response.py b/pinecone/core/client/model/describe_index_stats_response.py deleted file mode 100644 index 6e965ed90..000000000 --- a/pinecone/core/client/model/describe_index_stats_response.py +++ /dev/null @@ -1,291 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.namespace_summary import NamespaceSummary - - globals()["NamespaceSummary"] = NamespaceSummary - - -class DescribeIndexStatsResponse(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "namespaces": ({str: (NamespaceSummary,)},), # noqa: E501 - "dimension": (int,), # noqa: E501 - "index_fullness": (float,), # noqa: E501 - "total_vector_count": (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "namespaces": "namespaces", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "index_fullness": "indexFullness", # noqa: E501 - "total_vector_count": "totalVectorCount", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """DescribeIndexStatsResponse - 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,) - 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%.. [optional] # noqa: E501 - total_vector_count (int): [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 ApiTypeError( - "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 - """DescribeIndexStatsResponse - 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,) - 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%.. [optional] # noqa: E501 - total_vector_count (int): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/fetch_response.py b/pinecone/core/client/model/fetch_response.py deleted file mode 100644 index 37ed4b17a..000000000 --- a/pinecone/core/client/model/fetch_response.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.vector import Vector - - globals()["Vector"] = Vector - - -class FetchResponse(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "vectors": ({str: (Vector,)},), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "vectors": "vectors", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """FetchResponse - 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,) - vectors ({str: (Vector,)}): [optional] # noqa: E501 - namespace (str): The namespace of the vectors.. [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 ApiTypeError( - "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 - """FetchResponse - 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,) - vectors ({str: (Vector,)}): [optional] # noqa: E501 - namespace (str): The namespace of the vectors.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/hnsw_config.py b/pinecone/core/client/model/hnsw_config.py deleted file mode 100644 index ecf41422d..000000000 --- a/pinecone/core/client/model/hnsw_config.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class HnswConfig(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "ef_construction": (int,), # noqa: E501 - "ef": (int,), # noqa: E501 - "m": (int,), # noqa: E501 - "max_elements": (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "ef_construction": "ef_construction", # noqa: E501 - "ef": "ef", # noqa: E501 - "m": "M", # noqa: E501 - "max_elements": "max_elements", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """HnswConfig - 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,) - ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 - ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 - m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 - max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( - "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 - """HnswConfig - 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,) - ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 - ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 - m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 - max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/index_meta.py b/pinecone/core/client/model/index_meta.py deleted file mode 100644 index e2e9bd948..000000000 --- a/pinecone/core/client/model/index_meta.py +++ /dev/null @@ -1,279 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.index_meta_database import IndexMetaDatabase - - globals()["IndexMetaDatabase"] = IndexMetaDatabase - - -class IndexMeta(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "database": (IndexMetaDatabase,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "database": "database", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """IndexMeta - 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,) - database (IndexMetaDatabase): [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 ApiTypeError( - "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 - """IndexMeta - 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,) - database (IndexMetaDatabase): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/index_meta_database.py b/pinecone/core/client/model/index_meta_database.py deleted file mode 100644 index a969abd82..000000000 --- a/pinecone/core/client/model/index_meta_database.py +++ /dev/null @@ -1,319 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.index_meta_database_status import IndexMetaDatabaseStatus - - globals()["IndexMetaDatabaseStatus"] = IndexMetaDatabaseStatus - - -class IndexMetaDatabase(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "name": (str,), # noqa: E501 - "dimensions": (str,), # noqa: E501 - "index_type": (str,), # noqa: E501 - "metric": (str,), # noqa: E501 - "pods": (int,), # noqa: E501 - "replicas": (int,), # noqa: E501 - "shards": (int,), # noqa: E501 - "pod_type": (str,), # noqa: E501 - "index_config": (dict,), # noqa: E501 - "metadata_config": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - "status": (IndexMetaDatabaseStatus,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "name": "name", # noqa: E501 - "dimensions": "dimensions", # noqa: E501 - "index_type": "index_type", # noqa: E501 - "metric": "metric", # noqa: E501 - "pods": "pods", # noqa: E501 - "replicas": "replicas", # noqa: E501 - "shards": "shards", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - "index_config": "index_config", # noqa: E501 - "metadata_config": "metadata_config", # noqa: E501 - "status": "status", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """IndexMetaDatabase - 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,) - name (str): [optional] # noqa: E501 - dimensions (str): [optional] # noqa: E501 - index_type (str): [optional] # noqa: E501 - metric (str): [optional] # noqa: E501 - pods (int): [optional] # noqa: E501 - replicas (int): [optional] # noqa: E501 - shards (int): [optional] # noqa: E501 - pod_type (str): [optional] # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - status (IndexMetaDatabaseStatus): [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 ApiTypeError( - "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 - """IndexMetaDatabase - 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,) - name (str): [optional] # noqa: E501 - dimensions (str): [optional] # noqa: E501 - index_type (str): [optional] # noqa: E501 - metric (str): [optional] # noqa: E501 - pods (int): [optional] # noqa: E501 - replicas (int): [optional] # noqa: E501 - shards (int): [optional] # noqa: E501 - pod_type (str): [optional] # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - status (IndexMetaDatabaseStatus): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/index_meta_database_status.py b/pinecone/core/client/model/index_meta_database_status.py deleted file mode 100644 index 8430174fe..000000000 --- a/pinecone/core/client/model/index_meta_database_status.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class IndexMetaDatabaseStatus(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 = { - ("state",): { - "INITIALIZING": "Initializing", - "SCALINGUP": "ScalingUp", - "SCALINGDOWN": "ScalingDown", - "TERMINATING": "Terminating", - "READY": "Ready", - }, - } - - validations = {} - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "ready": (bool,), # noqa: E501 - "state": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "ready": "ready", # noqa: E501 - "state": "state", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """IndexMetaDatabaseStatus - 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,) - ready (bool): [optional] # noqa: E501 - state (str): [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 ApiTypeError( - "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 - """IndexMetaDatabaseStatus - 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,) - ready (bool): [optional] # noqa: E501 - state (str): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/index_meta_status.py b/pinecone/core/client/model/index_meta_status.py deleted file mode 100644 index c9da0214a..000000000 --- a/pinecone/core/client/model/index_meta_status.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone JSON API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class IndexMetaStatus(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "crashed": ([str],), # noqa: E501 - "ready": (bool,), # noqa: E501 - "port": (int,), # noqa: E501 - "waiting": ([str],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "crashed": "crashed", # noqa: E501 - "ready": "ready", # noqa: E501 - "port": "port", # noqa: E501 - "waiting": "waiting", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """IndexMetaStatus - 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,) - crashed ([str]): [optional] # noqa: E501 - ready (bool): [optional] # noqa: E501 - port (int): [optional] # noqa: E501 - waiting ([str]): [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 ApiTypeError( - "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 - """IndexMetaStatus - 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,) - crashed ([str]): [optional] # noqa: E501 - ready (bool): [optional] # noqa: E501 - port (int): [optional] # noqa: E501 - waiting ([str]): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/namespace_summary.py b/pinecone/core/client/model/namespace_summary.py deleted file mode 100644 index 869672d0a..000000000 --- a/pinecone/core/client/model/namespace_summary.py +++ /dev/null @@ -1,271 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class NamespaceSummary(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "vector_count": (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "vector_count": "vectorCount", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """NamespaceSummary - 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,) - vector_count (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.. [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 ApiTypeError( - "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 - """NamespaceSummary - 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,) - vector_count (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.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/patch_request.py b/pinecone/core/client/model/patch_request.py deleted file mode 100644 index ac67785d5..000000000 --- a/pinecone/core/client/model/patch_request.py +++ /dev/null @@ -1,275 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class PatchRequest(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "replicas": (int,), # noqa: E501 - "pod_type": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "replicas": "replicas", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """PatchRequest - 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,) - replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 - pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [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 ApiTypeError( - "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 - """PatchRequest - 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,) - replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 - pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/protobuf_any.py b/pinecone/core/client/model/protobuf_any.py deleted file mode 100644 index 220d4fc11..000000000 --- a/pinecone/core/client/model/protobuf_any.py +++ /dev/null @@ -1,275 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class ProtobufAny(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "type_url": (str,), # noqa: E501 - "value": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "type_url": "typeUrl", # noqa: E501 - "value": "value", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ProtobufAny - 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,) - type_url (str): [optional] # noqa: E501 - value (str): [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 ApiTypeError( - "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 - """ProtobufAny - 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,) - type_url (str): [optional] # noqa: E501 - value (str): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/protobuf_null_value.py b/pinecone/core/client/model/protobuf_null_value.py deleted file mode 100644 index 9cc94e881..000000000 --- a/pinecone/core/client/model/protobuf_null_value.py +++ /dev/null @@ -1,293 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class ProtobufNullValue(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - ("value",): { - "NULL_VALUE": "NULL_VALUE", - }, - } - - validations = {} - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "value": (str,), - } - - @cached_property - def discriminator(): - return None - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """ProtobufNullValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 - - Keyword Args: - value (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = "NULL_VALUE" - - _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 ApiTypeError( - "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 ApiTypeError( - "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): - """ProtobufNullValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 - - Keyword Args: - value (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = "NULL_VALUE" - - _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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/query_request.py b/pinecone/core/client/model/query_request.py deleted file mode 100644 index ec88c383c..000000000 --- a/pinecone/core/client/model/query_request.py +++ /dev/null @@ -1,329 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.query_vector import QueryVector - from pinecone.core.client.model.sparse_values import SparseValues - - globals()["QueryVector"] = QueryVector - globals()["SparseValues"] = SparseValues - - -class QueryRequest(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 = { - ("top_k",): { - "inclusive_maximum": 10000, - "inclusive_minimum": 1, - }, - ("queries",): {}, - ("vector",): {}, - ("id",): { - "max_length": 512, - }, - } - - @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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "top_k": (int,), # noqa: E501 - "namespace": (str,), # noqa: E501 - "filter": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - "include_values": (bool,), # noqa: E501 - "include_metadata": (bool,), # noqa: E501 - "queries": ([QueryVector],), # noqa: E501 - "vector": ([float],), # noqa: E501 - "sparse_vector": (SparseValues,), # noqa: E501 - "id": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "top_k": "topK", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "filter": "filter", # noqa: E501 - "include_values": "includeValues", # noqa: E501 - "include_metadata": "includeMetadata", # noqa: E501 - "queries": "queries", # noqa: E501 - "vector": "vector", # noqa: E501 - "sparse_vector": "sparseVector", # noqa: E501 - "id": "id", # 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 - """QueryRequest - a model defined in OpenAPI - - Args: - top_k (int): The number of results to return for each query. - - 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,) - namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [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 - vector ([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`.. [optional] # noqa: E501 - sparse_vector (SparseValues): [optional] # noqa: E501 - id (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`.. [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 ApiTypeError( - "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 - """QueryRequest - a model defined in OpenAPI - - Args: - top_k (int): The number of results to return for each query. - - 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,) - namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [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 - vector ([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`.. [optional] # noqa: E501 - sparse_vector (SparseValues): The sparse values of the query vector [optional] # noqa: E501 - id (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`.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/query_response.py b/pinecone/core/client/model/query_response.py deleted file mode 100644 index 855337627..000000000 --- a/pinecone/core/client/model/query_response.py +++ /dev/null @@ -1,289 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.scored_vector import ScoredVector - from pinecone.core.client.model.single_query_results import SingleQueryResults - - globals()["ScoredVector"] = ScoredVector - globals()["SingleQueryResults"] = SingleQueryResults - - -class QueryResponse(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "results": ([SingleQueryResults],), # noqa: E501 - "matches": ([ScoredVector],), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "results": "results", # noqa: E501 - "matches": "matches", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """QueryResponse - 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,) - results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 - matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 - namespace (str): The namespace for the vectors.. [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 ApiTypeError( - "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 - """QueryResponse - 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,) - results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 - matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 - namespace (str): The namespace for the vectors.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/query_vector.py b/pinecone/core/client/model/query_vector.py deleted file mode 100644 index 5d52522ec..000000000 --- a/pinecone/core/client/model/query_vector.py +++ /dev/null @@ -1,307 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -class QueryVector(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 = { - ("values",): {}, - ("top_k",): { - "inclusive_maximum": 10000, - "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 - """ - lazy_import() - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "values": ([float],), # noqa: E501 - "sparse_values": (SparseValues,), # noqa: E501 - "top_k": (int,), # noqa: E501 - "namespace": (str,), # noqa: E501 - "filter": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "top_k": "topK", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "filter": "filter", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, values, *args, **kwargs): # noqa: E501 - """QueryVector - a model defined in OpenAPI - - Args: - values ([float]): The query vector values. This should be the same length as the dimension of the index being queried. - - 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,) - sparse_values (SparseValues): The sparse data of the query vector [optional] # noqa: E501 - top_k (int): An override for the number of results to return for this query vector.. [optional] # noqa: E501 - namespace (str): An override the namespace to search.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): An override for the metadata filter to apply. This replaces the request-level filter.. [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 ApiTypeError( - "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.values = values - 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, values, *args, **kwargs): # noqa: E501 - """QueryVector - a model defined in OpenAPI - - Args: - values ([float]): The query vector values. This should be the same length as the dimension of the index being queried. - - 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,) - sparse_values (SparseValues): This is the sparse data of the vector [optional] # noqa: E501 - top_k (int): An override for the number of results to return for this query vector.. [optional] # noqa: E501 - namespace (str): An override the namespace to search.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): An override for the metadata filter to apply. This replaces the request-level filter.. [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 ApiTypeError( - "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.values = values - 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 ApiAttributeError( - 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/client/model/rpc_status.py b/pinecone/core/client/model/rpc_status.py deleted file mode 100644 index 6d0c7605a..000000000 --- a/pinecone/core/client/model/rpc_status.py +++ /dev/null @@ -1,287 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.protobuf_any import ProtobufAny - - globals()["ProtobufAny"] = ProtobufAny - - -class RpcStatus(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "code": (int,), # noqa: E501 - "message": (str,), # noqa: E501 - "details": ([ProtobufAny],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "code": "code", # noqa: E501 - "message": "message", # noqa: E501 - "details": "details", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """RpcStatus - 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,) - code (int): [optional] # noqa: E501 - message (str): [optional] # noqa: E501 - details ([ProtobufAny]): [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 ApiTypeError( - "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 - """RpcStatus - 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,) - code (int): [optional] # noqa: E501 - message (str): [optional] # noqa: E501 - details ([ProtobufAny]): [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/scored_vector.py b/pinecone/core/client/model/scored_vector.py deleted file mode 100644 index 98e7f9589..000000000 --- a/pinecone/core/client/model/scored_vector.py +++ /dev/null @@ -1,306 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -class ScoredVector(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 = { - ("id",): { - "max_length": 512, - "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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "id": (str,), # noqa: E501 - "score": (float,), # noqa: E501 - "values": ([float],), # noqa: E501 - "sparse_values": (SparseValues,), # noqa: E501 - "metadata": ({str: (bool, date, datetime, 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 - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "metadata": "metadata", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 - """ScoredVector - a model defined in OpenAPI - - Args: - id (str): This is the vector's unique id. - - 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,) - score (float): This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.. [optional] # noqa: E501 - values ([float]): This is the vector data, if it is requested.. [optional] # noqa: E501 - sparse_values (SparseValues): the sparse data of the vector [optional] # noqa: E501 - metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata, if it is requested.. [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 ApiTypeError( - "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 - """ScoredVector - a model defined in OpenAPI - - Args: - id (str): This is the vector's unique id. - - 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,) - score (float): This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.. [optional] # noqa: E501 - values ([float]): This is the vector data, if it is requested.. [optional] # noqa: E501 - sparse_values (SparseValues): This is the sparse data of the vector [optional] # noqa: E501 - metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata, if it is requested.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/single_query_results.py b/pinecone/core/client/model/single_query_results.py deleted file mode 100644 index 9ff572893..000000000 --- a/pinecone/core/client/model/single_query_results.py +++ /dev/null @@ -1,283 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.scored_vector import ScoredVector - - globals()["ScoredVector"] = ScoredVector - - -class SingleQueryResults(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "matches": ([ScoredVector],), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "matches": "matches", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """SingleQueryResults - 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,) - matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 - namespace (str): The namespace for the vectors.. [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 ApiTypeError( - "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 - """SingleQueryResults - 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,) - matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 - namespace (str): The namespace for the vectors.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/sparse_values.py b/pinecone/core/client/model/sparse_values.py deleted file mode 100644 index 08bc71338..000000000 --- a/pinecone/core/client/model/sparse_values.py +++ /dev/null @@ -1,286 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class SparseValues(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 = { - ("indices",): {}, - ("values",): {}, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "indices": ([int],), # noqa: E501 - "values": ([float],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "indices": "indices", # noqa: E501 - "values": "values", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, indices, values, *args, **kwargs): # noqa: E501 - """SparseValues - a model defined in OpenAPI - - Args: - indices ([int]): - values ([float]): - - 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 ApiTypeError( - "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.indices = indices - self.values = values - 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, indices, values, *args, **kwargs): # noqa: E501 - """SparseValues - a model defined in OpenAPI - - Args: - indices ([int]): - values ([float]): - - 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 ApiTypeError( - "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.indices = indices - self.values = values - 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 ApiAttributeError( - 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/client/model/update_request.py b/pinecone/core/client/model/update_request.py deleted file mode 100644 index 404ec38d4..000000000 --- a/pinecone/core/client/model/update_request.py +++ /dev/null @@ -1,307 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -class UpdateRequest(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 = { - ("id",): { - "max_length": 512, - "min_length": 1, - }, - ("values",): {}, - } - - @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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "id": (str,), # noqa: E501 - "values": ([float],), # noqa: E501 - "sparse_values": (SparseValues,), # noqa: E501 - "set_metadata": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "id": "id", # noqa: E501 - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "set_metadata": "setMetadata", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 - """UpdateRequest - a model defined in OpenAPI - - Args: - id (str): Vector's unique id. - - 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 ([float]): Vector data.. [optional] # noqa: E501 - sparse_values (SparseValues): This is the sparse data of the vector to update [optional] # noqa: E501 - set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 - namespace (str): Namespace name where to update the vector.. [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 ApiTypeError( - "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 - """UpdateRequest - a model defined in OpenAPI - - Args: - id (str): Vector's unique id. - - 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 ([float]): Vector data.. [optional] # noqa: E501 - sparse_values (SparseValues): This is the sparse data of the vector to update [optional] # noqa: E501 - set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 - namespace (str): Namespace name where to update the vector.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/upsert_request.py b/pinecone/core/client/model/upsert_request.py deleted file mode 100644 index 319900217..000000000 --- a/pinecone/core/client/model/upsert_request.py +++ /dev/null @@ -1,291 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.vector import Vector - - globals()["Vector"] = Vector - - -class UpsertRequest(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 = { - ("vectors",): {}, - } - - @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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "vectors": ([Vector],), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "vectors": "vectors", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, vectors, *args, **kwargs): # noqa: E501 - """UpsertRequest - a model defined in OpenAPI - - Args: - vectors ([Vector]): An array containing the vectors to upsert. Recommended batch limit is 100 vectors. - - 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,) - namespace (str): This is the namespace name where you upsert vectors.. [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 ApiTypeError( - "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.vectors = vectors - 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, vectors, *args, **kwargs): # noqa: E501 - """UpsertRequest - a model defined in OpenAPI - - Args: - vectors ([Vector]): An array containing the vectors to upsert. Recommended batch limit is 100 vectors. - - 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,) - namespace (str): This is the namespace name where you upsert vectors.. [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 ApiTypeError( - "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.vectors = vectors - 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 ApiAttributeError( - 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/client/model/upsert_response.py b/pinecone/core/client/model/upsert_response.py deleted file mode 100644 index b766ec431..000000000 --- a/pinecone/core/client/model/upsert_response.py +++ /dev/null @@ -1,271 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -class UpsertResponse(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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "upserted_count": (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "upserted_count": "upsertedCount", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """UpsertResponse - 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,) - upserted_count (int): The number of vectors upserted.. [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 ApiTypeError( - "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 - """UpsertResponse - 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,) - upserted_count (int): The number of vectors upserted.. [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 ApiTypeError( - "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 ApiAttributeError( - 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/client/model/vector.py b/pinecone/core/client/model/vector.py deleted file mode 100644 index 58a4dbea7..000000000 --- a/pinecone/core/client/model/vector.py +++ /dev/null @@ -1,305 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - -def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -class Vector(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 = { - ("id",): { - "max_length": 512, - "min_length": 1, - }, - ("values",): {}, - } - - @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, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "id": (str,), # noqa: E501 - "values": ([float],), # noqa: E501 - "sparse_values": (SparseValues,), # noqa: E501 - "metadata": ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - attribute_map = { - "id": "id", # noqa: E501 - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "metadata": "metadata", # noqa: E501 - } - - read_only_vars = {} - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, id, values, *args, **kwargs): # noqa: E501 - """Vector - a model defined in OpenAPI - - Args: - id (str): This is the vector's unique id. - values ([float]): This is the vector data included in the 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,) - sparse_values (SparseValues): the sparse data of the returned vector [optional] # noqa: E501 - metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata included in the request.. [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 ApiTypeError( - "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.values = values - 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, values, *args, **kwargs): # noqa: E501 - """Vector - a model defined in OpenAPI - - Args: - id (str): This is the vector's unique id. - values ([float]): This is the vector data included in the 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,) - sparse_values (SparseValues): This is the sparse data of the vector to update [optional] # noqa: E501 - metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata included in the request.. [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 ApiTypeError( - "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.values = values - 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 ApiAttributeError( - 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/client/model_utils.py b/pinecone/core/client/model_utils.py deleted file mode 100644 index 73dc385d5..000000000 --- a/pinecone/core/client/model_utils.py +++ /dev/null @@ -1,1884 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -from datetime import date, datetime # noqa: F401 -import inspect -import io -import os -import pprint -import re -import tempfile - -from dateutil.parser import parse - -from pinecone.core.client.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, -) - -none_type = type(None) -file_type = io.IOBase - - -def convert_js_args_to_python_args(fn): - from functools import wraps - - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get("_spec_property_naming", False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) - return fn(_self, *args, **kwargs) - - return wrapped_init - - -class cached_property(object): - # this caches the result of the function call for fn with no inputs - # use this as a decorator on function methods that you want converted - # into cached properties - result_key = "_results" - - def __init__(self, fn): - self._fn = fn - - def __get__(self, instance, cls=None): - if self.result_key in vars(self): - return vars(self)[self.result_key] - else: - result = self._fn() - setattr(self, self.result_key, result) - return result - - -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) - - -def allows_single_value_input(cls): - """ - This function returns True if the input composed schema model or any - descendant model allows a value only input - This is true for cases where oneOf contains items like: - oneOf: - - float - - NumberWithValidation - - StringEnum - - ArrayModel - - null - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return True - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas["oneOf"]: - return False - return any(allows_single_value_input(c) for c in cls._composed_schemas["oneOf"]) - return False - - -def composed_model_input_classes(cls): - """ - This function returns a list of the possible models that can be accepted as - inputs. - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return [cls] - elif issubclass(cls, ModelNormal): - if cls.discriminator is None: - return [cls] - else: - return get_discriminated_classes(cls) - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas["oneOf"]: - return [] - if cls.discriminator is None: - input_classes = [] - for c in cls._composed_schemas["oneOf"]: - input_classes.extend(composed_model_input_classes(c)) - return input_classes - else: - return get_discriminated_classes(cls) - return [] - - -class OpenApiModel(object): - """The base class for all OpenAPIModels""" - - def set_attribute(self, name, value): - # this is only used to set properties on self - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiAttributeError("{0} has no attribute '{1}'".format(type(self).__name__, name), path_to_item) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message(var_name=name, var_value=name, valid_classes=(str,), key_type=True) - raise ApiTypeError(error_msg, path_to_item=path_to_item, valid_classes=(str,), key_type=True) - - if self._check_type: - value = validate_and_convert_types( - value, - required_types_mixed, - path_to_item, - self._spec_property_naming, - self._check_type, - configuration=self._configuration, - ) - if (name,) in self.allowed_values: - check_allowed_values(self.allowed_values, (name,), value) - if (name,) in self.validations: - check_validations(self.validations, (name,), value, self._configuration) - self.__dict__["_data_store"][name] = value - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other - - def __setattr__(self, attr, value): - """set the value of an attribute using dot notation: `instance.attr = val`""" - self[attr] = value - - def __getattr__(self, attr): - """get the value of an attribute using dot notation: `instance.attr`""" - return self.get(attr) - - def __new__(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get("_visited_composed_classes", ()) - if cls.discriminator is None or cls in visited_composed_classes: - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: 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 the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return super(OpenApiModel, cls).__new__(cls) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get("_path_to_item", ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class(cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get("_path_to_item", ()) - disc_prop_value = kwargs.get(discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return super(OpenApiModel, cls).__new__(cls) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = cls._composed_schemas.get("oneOf", ()) + cls._composed_schemas.get("anyOf", ()) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs["_visited_composed_classes"] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get("allOf") and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = super(OpenApiModel, cls).__new__(cls) - self_inst.__init__(*args, **kwargs) - - new_inst = new_cls.__new__(new_cls, *args, **kwargs) - new_inst.__init__(*args, **kwargs) - return new_inst - - @classmethod - @convert_js_args_to_python_args - def _new_from_openapi_data(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get("_visited_composed_classes", ()) - if cls.discriminator is None or cls in visited_composed_classes: - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: 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 the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return cls._from_openapi_data(*args, **kwargs) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get("_path_to_item", ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class(cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get("_path_to_item", ()) - disc_prop_value = kwargs.get(discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return cls._from_openapi_data(*args, **kwargs) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = cls._composed_schemas.get("oneOf", ()) + cls._composed_schemas.get("anyOf", ()) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs["_visited_composed_classes"] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get("allOf") and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = cls._from_openapi_data(*args, **kwargs) - - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - return new_inst - - -class ModelSimple(OpenApiModel): - """the parent class of models whose type != object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__["_data_store"].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__["_data_store"] - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - this_val = self._data_store["value"] - that_val = other._data_store["value"] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - return vals_equal - - -class ModelNormal(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__["_data_store"].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__["_data_store"] - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -class ModelComposed(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi and have oneOf/allOf/anyOf - - When one sets a property we use var_name_to_model_instances to store the value in - the correct class instances + run any type checking + validation code. - When one gets a property we use var_name_to_model_instances to get the value - from the correct class instances. - This allows multiple composed schemas to contain the same property with additive - constraints on the value. - - _composed_schemas (dict) stores the anyOf/allOf/oneOf classes - key (str): allOf/oneOf/anyOf - value (list): the classes in the XOf definition. - Note: none_type can be included when the openapi document version >= 3.1.0 - _composed_instances (list): stores a list of instances of the composed schemas - defined in _composed_schemas. When properties are accessed in the self instance, - they are returned from the self._data_store or the data stores in the instances - in self._composed_schemas - _var_name_to_model_instances (dict): maps between a variable name on self and - the composed instances (self included) which contain that data - key (str): property name - value (list): list of class instances, self or instances in _composed_instances - which contain the value that the key is referring to. - """ - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - """ - Use cases: - 1. additional_properties_type is None (additionalProperties == False in spec) - Check for property presence in self.openapi_types - if not present then throw an error - if present set in self, set attribute - always set on composed schemas - 2. additional_properties_type exists - set attribute on self - always set on composed schemas - """ - if self.additional_properties_type is None: - """ - For an attribute to exist on a composed schema it must: - - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND - - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - - schema_requirements: - For an attribute to exist on a schema it must: - - be present in properties at the schema OR - - have additionalProperties unset (defaults additionalProperties = any type) OR - - have additionalProperties set - """ - if name not in self.openapi_types: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format(type(self).__name__, name), - [e for e in [self._path_to_item, name] if e], - ) - # attribute must be set on self and composed instances - self.set_attribute(name, value) - for model_instance in self._composed_instances: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__["_var_name_to_model_instances"][name] = self._composed_instances + [self] - return None - - __unset_attribute_value__ = object() - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get(name) - values = [] - # A composed model stores self and child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. - # Any property must exist in self and all model instances - # The value stored in all model instances must be the same - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - v = model_instance._data_store[name] - if v not in values: - values.append(v) - len_values = len(values) - if len_values == 0: - return default - elif len_values == 1: - return values[0] - elif len_values > 1: - raise ApiValueError( - "Values stored for property {0} in {1} differ when looking " - "at self and self's composed instances. All values must be " - "the same".format(name, type(self).__name__), - [e for e in [self._path_to_item, name] if e], - ) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - value = self.get(name, self.__unset_attribute_value__) - if value is self.__unset_attribute_value__: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format(type(self).__name__, name), - [e for e in [self._path_to_item, name] if e], - ) - return value - - def __contains__(self, name): - """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" - - if name in self.required_properties: - return name in self.__dict__ - - model_instances = self._var_name_to_model_instances.get(name, self._additional_properties_model_instances) - - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - return True - - return False - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -COERCION_INDEX_BY_TYPE = { - ModelComposed: 0, - ModelNormal: 1, - ModelSimple: 2, - none_type: 3, # The type of 'None'. - list: 4, - dict: 5, - float: 6, - int: 7, - bool: 8, - datetime: 9, - date: 10, - str: 11, - file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. -} - -# these are used to limit what type conversions we try to do -# when we have a valid type already and we want to try converting -# to another type -UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), - (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float. - (list, ModelComposed), - (dict, ModelComposed), - (str, ModelComposed), - (int, ModelComposed), - (float, ModelComposed), - (list, ModelComposed), - (list, ModelNormal), - (dict, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), -) - -COERCIBLE_TYPE_PAIRS = { - False: ( # client instantiation of a model with client data - # (dict, ModelComposed), - # (list, ModelComposed), - # (dict, ModelNormal), - # (list, ModelNormal), - # (str, ModelSimple), - # (int, ModelSimple), - # (float, ModelSimple), - # (list, ModelSimple), - # (str, int), - # (str, float), - # (str, datetime), - # (str, date), - # (int, str), - # (float, str), - ), - True: ( # server -> client data - (dict, ModelComposed), - (list, ModelComposed), - (dict, ModelNormal), - (list, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), - # (str, int), - # (str, float), - (str, datetime), - (str, date), - # (int, str), - # (float, str), - (str, file_type), - ), -} - - -def get_simple_class(input_value): - """Returns an input_value's simple class that we will use for type checking - Python2: - float and int will return int, where int is the python3 int backport - str and unicode will return str, where str is the python3 str backport - Note: float and int ARE both instances of int backport - Note: str_py2 and unicode_py2 are NOT both instances of str backport - - Args: - input_value (class/class_instance): the item for which we will return - the simple class - """ - if isinstance(input_value, type): - # input_value is a class - return input_value - elif isinstance(input_value, tuple): - return tuple - elif isinstance(input_value, list): - return list - elif isinstance(input_value, dict): - return dict - elif isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if isinstance(input_values, list) and not set(input_values).issubset(set(these_allowed_values)): - invalid_values = (", ".join(map(str, set(input_values) - set(these_allowed_values))),) - raise ApiValueError( - "Invalid values for `%s` [%s], must be a subset of [%s]" - % (input_variable_path[0], invalid_values, ", ".join(map(str, these_allowed_values))) - ) - elif isinstance(input_values, dict) and not set(input_values.keys()).issubset(set(these_allowed_values)): - invalid_values = ", ".join(map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( - "Invalid keys in `%s` [%s], must be a subset of [%s]" - % (input_variable_path[0], invalid_values, ", ".join(map(str, these_allowed_values))) - ) - elif not isinstance(input_values, (list, dict)) and input_values not in these_allowed_values: - raise ApiValueError( - "Invalid value for `%s` (%s), must be one of %s" - % (input_variable_path[0], input_values, these_allowed_values) - ) - - -def is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return ( - configuration is None - or not hasattr(configuration, "_disabled_client_side_validations") - or schema_keyword not in configuration._disabled_client_side_validations - ) - - -def check_validations(validations, input_variable_path, input_values, configuration=None): - """Raises an exception if the input_values are invalid - - Args: - validations (dict): the validation dictionary. - input_variable_path (tuple): the path to the input variable. - input_values (list/str/int/float/date/datetime): the values that we - are checking. - configuration (Configuration): the configuration class. - """ - - if input_values is None: - return - - current_validations = validations[input_variable_path] - if ( - is_json_validation_enabled("multipleOf", configuration) - and "multiple_of" in current_validations - and isinstance(input_values, (int, float)) - and not (float(input_values) / current_validations["multiple_of"]).is_integer() - ): - # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( - "Invalid value for `%s`, value must be a multiple of " - "`%s`" % (input_variable_path[0], current_validations["multiple_of"]) - ) - - if ( - is_json_validation_enabled("maxLength", configuration) - and "max_length" in current_validations - and len(input_values) > current_validations["max_length"] - ): - raise ApiValueError( - "Invalid value for `%s`, length must be less than or equal to " - "`%s`" % (input_variable_path[0], current_validations["max_length"]) - ) - - if ( - is_json_validation_enabled("minLength", configuration) - and "min_length" in current_validations - and len(input_values) < current_validations["min_length"] - ): - raise ApiValueError( - "Invalid value for `%s`, length must be greater than or equal to " - "`%s`" % (input_variable_path[0], current_validations["min_length"]) - ) - - if ( - is_json_validation_enabled("maxItems", configuration) - and "max_items" in current_validations - and len(input_values) > current_validations["max_items"] - ): - raise ApiValueError( - "Invalid value for `%s`, number of items must be less than or " - "equal to `%s`" % (input_variable_path[0], current_validations["max_items"]) - ) - - if ( - is_json_validation_enabled("minItems", configuration) - and "min_items" in current_validations - and len(input_values) < current_validations["min_items"] - ): - raise ValueError( - "Invalid value for `%s`, number of items must be greater than or " - "equal to `%s`" % (input_variable_path[0], current_validations["min_items"]) - ) - - items = ("exclusive_maximum", "inclusive_maximum", "exclusive_minimum", "inclusive_minimum") - if any(item in current_validations for item in items): - if isinstance(input_values, list): - max_val = max(input_values) - min_val = min(input_values) - elif isinstance(input_values, dict): - max_val = max(input_values.values()) - min_val = min(input_values.values()) - else: - max_val = input_values - min_val = input_values - - if ( - is_json_validation_enabled("exclusiveMaximum", configuration) - and "exclusive_maximum" in current_validations - and max_val >= current_validations["exclusive_maximum"] - ): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than `%s`" - % (input_variable_path[0], current_validations["exclusive_maximum"]) - ) - - if ( - is_json_validation_enabled("maximum", configuration) - and "inclusive_maximum" in current_validations - and max_val > current_validations["inclusive_maximum"] - ): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than or equal to " - "`%s`" % (input_variable_path[0], current_validations["inclusive_maximum"]) - ) - - if ( - is_json_validation_enabled("exclusiveMinimum", configuration) - and "exclusive_minimum" in current_validations - and min_val <= current_validations["exclusive_minimum"] - ): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than `%s`" - % (input_variable_path[0], current_validations["exclusive_maximum"]) - ) - - if ( - is_json_validation_enabled("minimum", configuration) - and "inclusive_minimum" in current_validations - and min_val < current_validations["inclusive_minimum"] - ): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than or equal " - "to `%s`" % (input_variable_path[0], current_validations["inclusive_minimum"]) - ) - flags = current_validations.get("regex", {}).get("flags", 0) - if ( - is_json_validation_enabled("pattern", configuration) - and "regex" in current_validations - and not re.search(current_validations["regex"]["pattern"], input_values, flags=flags) - ): - err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( - input_variable_path[0], - current_validations["regex"]["pattern"], - ) - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) - - -def order_response_types(required_types): - """Returns the required types sorted in coercion order - - Args: - required_types (list/tuple): collection of classes or instance of - list or dict with class information inside it. - - Returns: - (list): coercion order sorted collection of classes or instance - of list or dict with class information inside it. - """ - - def index_getter(class_or_instance): - if isinstance(class_or_instance, list): - return COERCION_INDEX_BY_TYPE[list] - elif isinstance(class_or_instance, dict): - return COERCION_INDEX_BY_TYPE[dict] - elif inspect.isclass(class_or_instance) and issubclass(class_or_instance, ModelComposed): - return COERCION_INDEX_BY_TYPE[ModelComposed] - elif inspect.isclass(class_or_instance) and issubclass(class_or_instance, ModelNormal): - return COERCION_INDEX_BY_TYPE[ModelNormal] - elif inspect.isclass(class_or_instance) and issubclass(class_or_instance, ModelSimple): - return COERCION_INDEX_BY_TYPE[ModelSimple] - elif class_or_instance in COERCION_INDEX_BY_TYPE: - return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) - - sorted_types = sorted(required_types, key=lambda class_or_instance: index_getter(class_or_instance)) - return sorted_types - - -def remove_uncoercible(required_types_classes, current_item, spec_property_naming, must_convert=True): - """Only keeps the type conversions that are possible - - Args: - required_types_classes (tuple): tuple of classes that are required - these should be ordered by COERCION_INDEX_BY_TYPE - 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 variables names in the input data are python - variable names in PEP-8 snake case. - current_item (any): the current item (input data) to be converted - - Keyword Args: - must_convert (bool): if True the item to convert is of the wrong - type and we want a big list of coercibles - if False, we want a limited list of coercibles - - Returns: - (list): the remaining coercible required types, classes only - """ - current_type_simple = get_simple_class(current_item) - - results_classes = [] - for required_type_class in required_types_classes: - # convert our models to OpenApiModel - required_type_class_simplified = required_type_class - if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelComposed): - required_type_class_simplified = ModelComposed - elif issubclass(required_type_class_simplified, ModelNormal): - required_type_class_simplified = ModelNormal - elif issubclass(required_type_class_simplified, ModelSimple): - required_type_class_simplified = ModelSimple - - if required_type_class_simplified == current_type_simple: - # don't consider converting to one's own class - continue - - class_pair = (current_type_simple, required_type_class_simplified) - if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: - results_classes.append(required_type_class) - elif class_pair in UPCONVERSION_TYPE_PAIRS: - results_classes.append(required_type_class) - return results_classes - - -def get_discriminated_classes(cls): - """ - Returns all the classes that a discriminator converts to - TODO: lru_cache this - """ - possible_classes = [] - key = list(cls.discriminator.keys())[0] - if is_type_nullable(cls): - possible_classes.append(cls) - for discr_cls in cls.discriminator[key].values(): - if hasattr(discr_cls, "discriminator") and discr_cls.discriminator is not None: - possible_classes.extend(get_discriminated_classes(discr_cls)) - else: - possible_classes.append(discr_cls) - return possible_classes - - -def get_possible_classes(cls, from_server_context): - # TODO: lru_cache this - possible_classes = [cls] - if from_server_context: - return possible_classes - if hasattr(cls, "discriminator") and cls.discriminator is not None: - possible_classes = [] - possible_classes.extend(get_discriminated_classes(cls)) - elif issubclass(cls, ModelComposed): - possible_classes.extend(composed_model_input_classes(cls)) - return possible_classes - - -def get_required_type_classes(required_types_mixed, spec_property_naming): - """Converts the tuple required_types into a tuple and a dict described - below - - Args: - required_types_mixed (tuple/list): will contain either classes or - instance of list or dict - spec_property_naming (bool): if True these values came from the - server, and we use the data types in our endpoints. - If False, we are client side and we need to include - oneOf and discriminator classes inside the data types in our endpoints - - Returns: - (valid_classes, dict_valid_class_to_child_types_mixed): - valid_classes (tuple): the valid classes that the current item - should be - dict_valid_class_to_child_types_mixed (dict): - valid_class (class): this is the key - child_types_mixed (list/dict/tuple): describes the valid child - types - """ - valid_classes = [] - child_req_types_by_current_type = {} - for required_type in required_types_mixed: - if isinstance(required_type, list): - valid_classes.append(list) - child_req_types_by_current_type[list] = required_type - elif isinstance(required_type, tuple): - valid_classes.append(tuple) - child_req_types_by_current_type[tuple] = required_type - elif isinstance(required_type, dict): - valid_classes.append(dict) - child_req_types_by_current_type[dict] = required_type[str] - else: - valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) - return tuple(valid_classes), child_req_types_by_current_type - - -def change_keys_js_to_python(input_dict, model_class): - """ - Converts from javascript_key keys in the input_dict to python_keys in - the output dict using the mapping in model_class. - If the input_dict contains a key which does not declared in the model_class, - the key is added to the output dict as is. The assumption is the model_class - may have undeclared properties (additionalProperties attribute in the OAS - document). - """ - - if getattr(model_class, "attribute_map", None) is None: - return input_dict - output_dict = {} - reversed_attr_map = {value: key for key, value in model_class.attribute_map.items()} - for javascript_key, value in input_dict.items(): - python_key = reversed_attr_map.get(javascript_key) - if python_key is None: - # if the key is unknown, it is in error or it is an - # additionalProperties variable - python_key = javascript_key - output_dict[python_key] = value - return output_dict - - -def get_type_error(var_value, path_to_item, valid_classes, key_type=False): - error_msg = type_error_message( - var_name=path_to_item[-1], var_value=var_value, valid_classes=valid_classes, key_type=key_type - ) - return ApiTypeError(error_msg, path_to_item=path_to_item, valid_classes=valid_classes, key_type=key_type) - - -def deserialize_primitive(data, klass, path_to_item): - """Deserializes string to primitive type. - - :param data: str/int/float - :param klass: str/class the class to convert to - - :return: int, float, str, bool, date, datetime - """ - additional_message = "" - try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 - and parsed_datetime.minute == 0 - and parsed_datetime.second == 0 - and parsed_datetime.tzinfo is None - and 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError("This is not a float") - return converted_value - except (OverflowError, ValueError) as ex: - # parse can raise OverflowError - raise ApiValueError( - "{0}Failed to parse {1} as {2}".format(additional_message, repr(data), klass.__name__), - path_to_item=path_to_item, - ) from ex - - -def get_discriminator_class(model_class, discr_name, discr_value, cls_visited): - """Returns the child class specified by the discriminator. - - Args: - model_class (OpenApiModel): the model class. - discr_name (string): the name of the discriminator property. - discr_value (any): the discriminator value. - cls_visited (list): list of model classes that have been visited. - Used to determine the discriminator class without - visiting circular references indefinitely. - - Returns: - used_model_class (class/None): the chosen child class that will be used - to deserialize the data, for example dog.Dog. - If a class is not found, None is returned. - """ - - if model_class in cls_visited: - # The class has already been visited and no suitable class was found. - return None - cls_visited.append(model_class) - used_model_class = None - if discr_name in model_class.discriminator: - class_name_to_discr_class = model_class.discriminator[discr_name] - used_model_class = class_name_to_discr_class.get(discr_value) - if used_model_class is None: - # We didn't find a discriminated class in class_name_to_discr_class. - # So look in the ancestor or descendant discriminators - # The discriminator mapping may exist in a descendant (anyOf, oneOf) - # or ancestor (allOf). - # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat - # hierarchy, the discriminator mappings may be defined at any level - # in the hierarchy. - # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig - # if we try to make BasquePig from mammal, we need to travel through - # the oneOf descendant discriminators to find BasquePig - descendant_classes = model_class._composed_schemas.get("oneOf", ()) + model_class._composed_schemas.get( - "anyOf", () - ) - ancestor_classes = model_class._composed_schemas.get("allOf", ()) - possible_classes = descendant_classes + ancestor_classes - for cls in possible_classes: - # Check if the schema has inherited discriminators. - if hasattr(cls, "discriminator") and cls.discriminator is not None: - used_model_class = get_discriminator_class(cls, discr_name, discr_value, cls_visited) - if used_model_class is not None: - return used_model_class - return used_model_class - - -def deserialize_model(model_data, model_class, path_to_item, check_type, configuration, spec_property_naming): - """Deserializes model_data to model instance. - - Args: - model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model - model_class (OpenApiModel): the model class - path_to_item (list): path to the model in the received data - check_type (bool): whether to check the data tupe for the values in - the model - configuration (Configuration): the instance to use to convert files - 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 variables names in the input data are python - variable names in PEP-8 snake case. - - Returns: - model instance - - Raise: - ApiTypeError - ApiValueError - ApiKeyError - """ - - kw_args = dict( - _check_type=check_type, - _path_to_item=path_to_item, - _configuration=configuration, - _spec_property_naming=spec_property_naming, - ) - - if issubclass(model_class, ModelSimple): - return model_class._new_from_openapi_data(model_data, **kw_args) - elif isinstance(model_data, list): - return model_class._new_from_openapi_data(*model_data, **kw_args) - if isinstance(model_data, dict): - kw_args.update(model_data) - return model_class._new_from_openapi_data(**kw_args) - elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class._new_from_openapi_data(model_data, **kw_args) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode("utf-8") - f.write(response_data) - - f = open(path, "rb") - return f - - -def attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=True, -): - """ - Args: - input_value (any): the data to convert - valid_classes (any): the classes that are valid - path_to_item (list): the path to the item to convert - configuration (Configuration): the instance to use to convert files - 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 variables names in the input data are python - variable names in PEP-8 snake case. - key_type (bool): if True we need to convert a key type (not supported) - must_convert (bool): if True we must convert - check_type (bool): if True we check the type or the returned data in - ModelComposed/ModelNormal/ModelSimple instances - - Returns: - instance (any) the fixed item - - Raises: - ApiTypeError - ApiValueError - ApiKeyError - """ - valid_classes_ordered = order_response_types(valid_classes) - valid_classes_coercible = remove_uncoercible(valid_classes_ordered, input_value, spec_property_naming) - if not valid_classes_coercible or key_type: - # we do not handle keytype errors, json will take care - # of this for us - if configuration is None or not configuration.discard_unknown_keys: - raise get_type_error(input_value, path_to_item, valid_classes, key_type=key_type) - for valid_class in valid_classes_coercible: - try: - if issubclass(valid_class, OpenApiModel): - return deserialize_model( - input_value, valid_class, path_to_item, check_type, configuration, spec_property_naming - ) - elif valid_class == file_type: - return deserialize_file(input_value, configuration) - return deserialize_primitive(input_value, valid_class, path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: - if must_convert: - raise conversion_exc - # if we have conversion errors when must_convert == False - # we ignore the exception and move on to the next class - continue - # we were unable to convert, must_convert == False - return input_value - - -def is_type_nullable(input_type): - """ - Returns true if None is an allowed value for the specified input_type. - - A type is nullable if at least one of the following conditions is true: - 1. The OAS 'nullable' attribute has been specified, - 1. The type is the 'null' type, - 1. The type is a anyOf/oneOf composed schema, and a child schema is - the 'null' type. - Args: - input_type (type): the class of the input_value that we are - checking - Returns: - bool - """ - if input_type is none_type: - return True - if issubclass(input_type, OpenApiModel) and input_type._nullable: - return True - if issubclass(input_type, ModelComposed): - # If oneOf/anyOf, check if the 'null' type is one of the allowed types. - for t in input_type._composed_schemas.get("oneOf", ()): - if is_type_nullable(t): - return True - for t in input_type._composed_schemas.get("anyOf", ()): - if is_type_nullable(t): - return True - return False - - -def is_valid_type(input_class_simple, valid_classes): - """ - Args: - input_class_simple (class): the class of the input_value that we are - checking - valid_classes (tuple): the valid classes that the current item - should be - Returns: - bool - """ - valid_type = input_class_simple in valid_classes - if not valid_type and (issubclass(input_class_simple, OpenApiModel) or input_class_simple is none_type): - for valid_class in valid_classes: - if input_class_simple is none_type and is_type_nullable(valid_class): - # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. - return True - if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): - continue - discr_propertyname_py = list(valid_class.discriminator.keys())[0] - discriminator_classes = valid_class.discriminator[discr_propertyname_py].values() - valid_type = is_valid_type(input_class_simple, discriminator_classes) - if valid_type: - return True - return valid_type - - -def validate_and_convert_types( - input_value, required_types_mixed, path_to_item, spec_property_naming, _check_type, configuration=None -): - """Raises a TypeError is there is a problem, otherwise returns value - - Args: - input_value (any): the data to validate/convert - required_types_mixed (list/dict/tuple): A list of - valid classes, or a list tuples of valid classes, or a dict where - the value is a tuple of value classes - path_to_item: (list) the path to the data being validated - this stores a list of keys or indices to get to the data being - validated - 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 variables names in the input data are python - variable names in PEP-8 snake case. - _check_type: (boolean) if true, type will be checked and conversion - will be attempted. - configuration: (Configuration): the configuration class to use - when converting file_type items. - If passed, conversion will be attempted when possible - If not passed, no conversions will be attempted and - exceptions will be raised - - Returns: - the correctly typed value - - Raises: - ApiTypeError - """ - results = get_required_type_classes(required_types_mixed, spec_property_naming) - valid_classes, child_req_types_by_current_type = results - - input_class_simple = get_simple_class(input_value) - valid_type = is_valid_type(input_class_simple, valid_classes) - if not valid_type: - if configuration: - # if input_value is not valid_type try to convert it - converted_instance = attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=True, - check_type=_check_type, - ) - return converted_instance - else: - raise get_type_error(input_value, path_to_item, valid_classes, key_type=False) - - # input_value's type is in valid_classes - if len(valid_classes) > 1 and configuration: - # there are valid classes which are not the current class - valid_classes_coercible = remove_uncoercible( - valid_classes, input_value, spec_property_naming, must_convert=False - ) - if valid_classes_coercible: - converted_instance = attempt_convert_item( - input_value, - valid_classes_coercible, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=_check_type, - ) - return converted_instance - - if child_req_types_by_current_type == {}: - # all types are of the required types and there are no more inner - # variables left to look at - return input_value - inner_required_types = child_req_types_by_current_type.get(type(input_value)) - if inner_required_types is None: - # for this type, there are not more inner variables left to look at - return input_value - if isinstance(input_value, list): - if input_value == []: - # allow an empty list - return input_value - for index, inner_value in enumerate(input_value): - inner_path = list(path_to_item) - inner_path.append(index) - input_value[index] = validate_and_convert_types( - inner_value, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration, - ) - elif isinstance(input_value, dict): - if input_value == {}: - # allow an empty dict - return input_value - for inner_key, inner_val in input_value.items(): - inner_path = list(path_to_item) - inner_path.append(inner_key) - if get_simple_class(inner_key) != str: - raise get_type_error(inner_key, inner_path, valid_classes, key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration, - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], model_to_dict(item[1], serialize=serialize)) - if hasattr(item[1], "_data_store") - else item, - value.items(), - ) - ) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, "_data_store"): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = "value" - if key_type: - key_or_value = "key" - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = "Invalid type for variable '{0}'. Required {1} type {2} and " "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed""" - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return "is {0}".format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas["allOf"]: - try: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise ApiValueError( - "Invalid inputs given to generate an instance of '%s'. The " - "input data was invalid for the allOf schema '%s' in the composed " - "schema '%s'. Error=%s" % (allof_class.__name__, allof_class.__name__, self.__class__.__name__, str(ex)) - ) from ex - return composed_instances - - -def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): - """ - Find the oneOf schema that matches the input data (e.g. payload). - If exactly one schema matches the input data, an instance of that schema - is returned. - If zero or more than one schema match the input data, an exception is raised. - In OAS 3.x, the payload MUST, by validation, match exactly one of the - schemas described by oneOf. - - Args: - cls: the class we are handling - model_kwargs (dict): var_name to var_value - The input data, e.g. the payload that must match a oneOf schema - in the OpenAPI document. - constant_kwargs (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): - the value to assign to a primitive class or ModelSimple class - Notes: - - this is only passed in when oneOf includes types which are not object - - None is used to suppress handling of model_arg, nullable models are handled in __new__ - - Returns - oneof_instance (instance) - """ - if len(cls._composed_schemas["oneOf"]) == 0: - return None - - oneof_instances = [] - # Iterate over each oneOf schema and determine if the input data - # matches the oneOf schemas. - for oneof_class in cls._composed_schemas["oneOf"]: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if oneof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - single_value_input = allows_single_value_input(oneof_class) - - try: - if not single_value_input: - oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) - else: - if issubclass(oneof_class, ModelSimple): - oneof_instance = oneof_class(model_arg, **constant_kwargs) - elif oneof_class in PRIMITIVE_TYPES: - oneof_instance = validate_and_convert_types( - model_arg, - (oneof_class,), - constant_kwargs["_path_to_item"], - constant_kwargs["_spec_property_naming"], - constant_kwargs["_check_type"], - configuration=constant_kwargs["_configuration"], - ) - oneof_instances.append(oneof_instance) - except Exception: - pass - if len(oneof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None " - "of the oneOf schemas matched the input data." % cls.__name__ - ) - elif len(oneof_instances) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. Multiple " - "oneOf schemas matched the inputs, but a max of one is allowed." % cls.__name__ - ) - return oneof_instances[0] - - -def get_anyof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - The input data, e.g. the payload that must match at least one - anyOf child schema in the OpenAPI document. - constant_args (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Returns - anyof_instances (list) - """ - anyof_instances = [] - if len(self._composed_schemas["anyOf"]) == 0: - return anyof_instances - - for anyof_class in self._composed_schemas["anyOf"]: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if anyof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - try: - anyof_instance = anyof_class(**model_args, **constant_args) - anyof_instances.append(anyof_instance) - except Exception: - pass - if len(anyof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None of the " - "anyOf schemas matched the inputs." % self.__class__.__name__ - ) - return anyof_instances - - -def get_discarded_args(self, composed_instances, model_args): - """ - Gathers the args that were discarded by configuration.discard_unknown_keys - """ - model_arg_keys = model_args.keys() - discarded_args = set() - # arguments passed to self were already converted to python names - # before __init__ was called - for instance in composed_instances: - if instance.__class__ in self._composed_schemas["allOf"]: - try: - keys = instance.to_dict().keys() - discarded_keys = model_args - keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - else: - try: - all_keys = set(model_to_dict(instance, serialize=False).keys()) - js_keys = model_to_dict(instance, serialize=True).keys() - all_keys.update(js_keys) - discarded_keys = model_arg_keys - all_keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - return discarded_args - - -def validate_get_composed_info(constant_args, model_args, self): - """ - For composed schemas, generate schema instances for - all schemas in the oneOf/anyOf/allOf definition. If additional - properties are allowed, also assign those properties on - all matched schemas that contain additionalProperties. - Openapi schemas are python classes. - - Exceptions are raised if: - - 0 or > 1 oneOf schema matches the model_args input data - - no anyOf schema matches the model_args input data - - any of the allOf schemas do not match the model_args input data - - Args: - constant_args (dict): these are the args that every model requires - model_args (dict): these are the required and optional spec args that - were passed in to make this model - self (class): the class that we are instantiating - This class contains self._composed_schemas - - Returns: - composed_info (list): length three - composed_instances (list): the composed instances which are not - self - var_name_to_model_instances (dict): a dict going from var_name - to the model_instance which holds that var_name - the model_instance may be self or an instance of one of the - classes in self.composed_instances() - additional_properties_model_instances (list): a list of the - model instances which have the property - additional_properties_type. This list can include self - """ - # create composed_instances - composed_instances = [] - allof_instances = get_allof_instances(self, model_args, constant_args) - composed_instances.extend(allof_instances) - oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) - if oneof_instance is not None: - composed_instances.append(oneof_instance) - anyof_instances = get_anyof_instances(self, model_args, constant_args) - composed_instances.extend(anyof_instances) - """ - set additional_properties_model_instances - additional properties must be evaluated at the schema level - so self's additional properties are most important - If self is a composed schema with: - - no properties defined in self - - additionalProperties: False - Then for object payloads every property is an additional property - and they are not allowed, so only empty dict is allowed - - Properties must be set on all matching schemas - so when a property is assigned toa composed instance, it must be set on all - composed instances regardless of additionalProperties presence - keeping it to prevent breaking changes in v5.0.1 - TODO remove cls._additional_properties_model_instances in 6.0.0 - """ - additional_properties_model_instances = [] - if self.additional_properties_type is not None: - additional_properties_model_instances = [self] - - """ - no need to set properties on self in here, they will be set in __init__ - By here all composed schema oneOf/anyOf/allOf instances have their properties set using - model_args - """ - discarded_args = get_discarded_args(self, composed_instances, model_args) - - # map variable names to composed_instances - var_name_to_model_instances = {} - for prop_name in model_args: - if prop_name not in discarded_args: - var_name_to_model_instances[prop_name] = [self] + composed_instances - - return [composed_instances, var_name_to_model_instances, additional_properties_model_instances, discarded_args] diff --git a/pinecone/core/client/models/__init__.py b/pinecone/core/client/models/__init__.py index 23c7ef034..85b949812 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -1,38 +1,47 @@ +# coding: utf-8 + # flake8: noqa +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -# import all models into this package -# if you have many models here with many references from one model to another this may -# raise a RecursionError -# to avoid this, import only the models that you directly need like: -# from from pinecone.core.client.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) -from pinecone.core.client.model.approximated_config import ApproximatedConfig -from pinecone.core.client.model.collection_meta import CollectionMeta -from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_request import CreateRequest -from pinecone.core.client.model.delete_request import DeleteRequest -from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.model.fetch_response import FetchResponse -from pinecone.core.client.model.hnsw_config import HnswConfig -from pinecone.core.client.model.index_meta import IndexMeta -from pinecone.core.client.model.index_meta_database import IndexMetaDatabase -from pinecone.core.client.model.index_meta_database_status import IndexMetaDatabaseStatus -from pinecone.core.client.model.namespace_summary import NamespaceSummary -from pinecone.core.client.model.patch_request import PatchRequest -from pinecone.core.client.model.protobuf_any import ProtobufAny -from pinecone.core.client.model.protobuf_null_value import ProtobufNullValue -from pinecone.core.client.model.query_request import QueryRequest -from pinecone.core.client.model.query_response import QueryResponse -from pinecone.core.client.model.query_vector import QueryVector -from pinecone.core.client.model.rpc_status import RpcStatus -from pinecone.core.client.model.scored_vector import ScoredVector -from pinecone.core.client.model.single_query_results import SingleQueryResults -from pinecone.core.client.model.sparse_values import SparseValues -from pinecone.core.client.model.update_request import UpdateRequest -from pinecone.core.client.model.upsert_request import UpsertRequest -from pinecone.core.client.model.upsert_response import UpsertResponse -from pinecone.core.client.model.vector import Vector +# import models into model package +from pinecone.core.client.models.approximated_config import ApproximatedConfig +from pinecone.core.client.models.collection_meta import CollectionMeta +from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.core.client.models.create_request import CreateRequest +from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig +from pinecone.core.client.models.delete_request import DeleteRequest +from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.models.fetch_response import FetchResponse +from pinecone.core.client.models.hnsw_config import HnswConfig +from pinecone.core.client.models.index_meta import IndexMeta +from pinecone.core.client.models.index_meta_database import IndexMetaDatabase +from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig +from pinecone.core.client.models.index_meta_status import IndexMetaStatus +from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response +from pinecone.core.client.models.namespace_summary import NamespaceSummary +from pinecone.core.client.models.patch_request import PatchRequest +from pinecone.core.client.models.protobuf_any import ProtobufAny +from pinecone.core.client.models.protobuf_null_value import ProtobufNullValue +from pinecone.core.client.models.query_request import QueryRequest +from pinecone.core.client.models.query_response import QueryResponse +from pinecone.core.client.models.query_vector import QueryVector +from pinecone.core.client.models.rpc_status import RpcStatus +from pinecone.core.client.models.scored_vector import ScoredVector +from pinecone.core.client.models.single_query_results import SingleQueryResults +from pinecone.core.client.models.sparse_values import SparseValues +from pinecone.core.client.models.update_request import UpdateRequest +from pinecone.core.client.models.upsert_request import UpsertRequest +from pinecone.core.client.models.upsert_response import UpsertResponse +from pinecone.core.client.models.vector import Vector diff --git a/pinecone/core/client/models/approximated_config.py b/pinecone/core/client/models/approximated_config.py new file mode 100644 index 000000000..3a478f77d --- /dev/null +++ b/pinecone/core/client/models/approximated_config.py @@ -0,0 +1,74 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictBool, StrictInt + + +class ApproximatedConfig(BaseModel): + """ + ApproximatedConfig + """ + + k_bits: Optional[StrictInt] = 512 + hybrid: Optional[StrictBool] = False + __properties = ["k_bits", "hybrid"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ApproximatedConfig: + """Create an instance of ApproximatedConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ApproximatedConfig: + """Create an instance of ApproximatedConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ApproximatedConfig.parse_obj(obj) + + _obj = ApproximatedConfig.parse_obj( + { + "k_bits": obj.get("k_bits") if obj.get("k_bits") is not None else 512, + "hybrid": obj.get("hybrid") if obj.get("hybrid") is not None else False, + } + ) + return _obj diff --git a/pinecone/core/client/models/collection_meta.py b/pinecone/core/client/models/collection_meta.py new file mode 100644 index 000000000..98ef3b0bd --- /dev/null +++ b/pinecone/core/client/models/collection_meta.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from pydantic import BaseModel, Field, StrictInt, StrictStr + + +class CollectionMeta(BaseModel): + """ + CollectionMeta + """ + + name: StrictStr = Field(...) + size: StrictInt = Field(..., description="The size of the collection in bytes.") + status: StrictStr = Field(..., description="The status of the collection.") + dimension: StrictInt = Field(..., description="The dimension of the records stored in the collection") + vector_count: StrictInt = Field(..., description="The number of records stored in the collection") + __properties = ["name", "size", "status", "dimension", "vector_count"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> CollectionMeta: + """Create an instance of CollectionMeta from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> CollectionMeta: + """Create an instance of CollectionMeta from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return CollectionMeta.parse_obj(obj) + + _obj = CollectionMeta.parse_obj( + { + "name": obj.get("name"), + "size": obj.get("size"), + "status": obj.get("status"), + "dimension": obj.get("dimension"), + "vector_count": obj.get("vector_count"), + } + ) + return _obj diff --git a/pinecone/core/client/models/create_collection_request.py b/pinecone/core/client/models/create_collection_request.py new file mode 100644 index 000000000..4ca482296 --- /dev/null +++ b/pinecone/core/client/models/create_collection_request.py @@ -0,0 +1,68 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from pydantic import BaseModel, Field, StrictStr + + +class CreateCollectionRequest(BaseModel): + """ + CreateCollectionRequest + """ + + name: StrictStr = Field(..., description="The name of the collection to be created.") + source: StrictStr = Field(..., description="The name of the index to be used as the source for the collection.") + __properties = ["name", "source"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> CreateCollectionRequest: + """Create an instance of CreateCollectionRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> CreateCollectionRequest: + """Create an instance of CreateCollectionRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return CreateCollectionRequest.parse_obj(obj) + + _obj = CreateCollectionRequest.parse_obj({"name": obj.get("name"), "source": obj.get("source")}) + return _obj diff --git a/pinecone/core/client/models/create_request.py b/pinecone/core/client/models/create_request.py new file mode 100644 index 000000000..9c6c95170 --- /dev/null +++ b/pinecone/core/client/models/create_request.py @@ -0,0 +1,149 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, validator +from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig + + +class CreateRequest(BaseModel): + """ + CreateRequest + """ + + name: StrictStr = Field( + ..., description="The name of the index to be created. The maximum length is 45 characters." + ) + dimension: StrictInt = Field(..., description="The dimensions of the vectors to be inserted in the index") + region: StrictStr = Field(..., description="The region where you would like your index to be created") + cloud: StrictStr = Field(..., description="The public cloud where you would like your index hosted") + capacity_mode: StrictStr = Field(..., description="The capacity mode for the index") + index_type: Optional[StrictStr] = Field( + "approximated", description="The type of vector index. Pinecone supports 'approximated'." + ) + metric: Optional[StrictStr] = Field( + "cosine", + description="The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.", + ) + pods: Optional[StrictInt] = Field(1, description="The number of pods for the index to use,including replicas.") + replicas: Optional[StrictInt] = Field( + 1, + description="The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.", + ) + shards: Optional[StrictInt] = Field(1, description="The number of shards to be used in the index.") + pod_type: Optional[StrictStr] = Field( + "p1.x1", + description="The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.", + ) + index_config: Optional[CreateRequestIndexConfig] = None + metadata_config: Optional[Dict[str, Any]] = Field( + None, + description='Configuration for the behavior of Pinecone\'s internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {"indexed": ["example_metadata_field"]} ``` ', + ) + source_collection: Optional[StrictStr] = Field( + None, description="The name of the collection to create an index from" + ) + __properties = [ + "name", + "dimension", + "region", + "cloud", + "capacity_mode", + "index_type", + "metric", + "pods", + "replicas", + "shards", + "pod_type", + "index_config", + "metadata_config", + "source_collection", + ] + + @validator("cloud") + def cloud_validate_enum(cls, value): + """Validates the enum""" + if value not in ("gcp", "aws", "azure"): + raise ValueError("must be one of enum values ('gcp', 'aws', 'azure')") + return value + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> CreateRequest: + """Create an instance of CreateRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of index_config + if self.index_config: + _dict["index_config"] = self.index_config.to_dict() + # set to None if metadata_config (nullable) is None + # and __fields_set__ contains the field + if self.metadata_config is None and "metadata_config" in self.__fields_set__: + _dict["metadata_config"] = None + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> CreateRequest: + """Create an instance of CreateRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return CreateRequest.parse_obj(obj) + + _obj = CreateRequest.parse_obj( + { + "name": obj.get("name"), + "dimension": obj.get("dimension"), + "region": obj.get("region"), + "cloud": obj.get("cloud"), + "capacity_mode": obj.get("capacity_mode"), + "index_type": obj.get("index_type") if obj.get("index_type") is not None else "approximated", + "metric": obj.get("metric") if obj.get("metric") is not None else "cosine", + "pods": obj.get("pods") if obj.get("pods") is not None else 1, + "replicas": obj.get("replicas") if obj.get("replicas") is not None else 1, + "shards": obj.get("shards") if obj.get("shards") is not None else 1, + "pod_type": obj.get("pod_type") if obj.get("pod_type") is not None else "p1.x1", + "index_config": CreateRequestIndexConfig.from_dict(obj.get("index_config")) + if obj.get("index_config") is not None + else None, + "metadata_config": obj.get("metadata_config"), + "source_collection": obj.get("source_collection"), + } + ) + return _obj diff --git a/pinecone/core/client/models/create_request_index_config.py b/pinecone/core/client/models/create_request_index_config.py new file mode 100644 index 000000000..091fd207e --- /dev/null +++ b/pinecone/core/client/models/create_request_index_config.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from pinecone.core.client.models.approximated_config import ApproximatedConfig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +CREATEREQUESTINDEXCONFIG_ONE_OF_SCHEMAS = ["ApproximatedConfig"] + + +class CreateRequestIndexConfig(BaseModel): + """ + CreateRequestIndexConfig + """ + + # data type: ApproximatedConfig + oneof_schema_1_validator: Optional[ApproximatedConfig] = None + if TYPE_CHECKING: + actual_instance: Union[ApproximatedConfig] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(CREATEREQUESTINDEXCONFIG_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator("actual_instance") + def actual_instance_must_validate_oneof(cls, v): + instance = CreateRequestIndexConfig.construct() + error_messages = [] + match = 0 + # validate data type: ApproximatedConfig + if not isinstance(v, ApproximatedConfig): + error_messages.append(f"Error! Input type `{type(v)}` is not `ApproximatedConfig`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when setting `actual_instance` in CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when setting `actual_instance` in CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> CreateRequestIndexConfig: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> CreateRequestIndexConfig: + """Returns the object represented by the json string""" + instance = CreateRequestIndexConfig.construct() + error_messages = [] + match = 0 + + # deserialize data into ApproximatedConfig + try: + instance.actual_instance = ApproximatedConfig.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when deserializing the JSON string into CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when deserializing the JSON string into CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) diff --git a/pinecone/core/client/models/delete_request.py b/pinecone/core/client/models/delete_request.py new file mode 100644 index 000000000..9e189c8bf --- /dev/null +++ b/pinecone/core/client/models/delete_request.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional +from pydantic import BaseModel, Field, StrictBool, StrictStr, conlist + + +class DeleteRequest(BaseModel): + """ + The request for the `Delete` operation. # noqa: E501 + """ + + ids: Optional[conlist(StrictStr)] = Field(None, description="Vectors to delete.") + delete_all: Optional[StrictBool] = Field( + False, + alias="deleteAll", + description="This indicates that all vectors in the index namespace should be deleted.", + ) + namespace: Optional[StrictStr] = Field(None, description="The namespace to delete vectors from, if applicable.") + filter: Optional[Dict[str, Any]] = Field( + None, + description="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/.", + ) + __properties = ["ids", "deleteAll", "namespace", "filter"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> DeleteRequest: + """Create an instance of DeleteRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> DeleteRequest: + """Create an instance of DeleteRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return DeleteRequest.parse_obj(obj) + + _obj = DeleteRequest.parse_obj( + { + "ids": obj.get("ids"), + "delete_all": obj.get("deleteAll") if obj.get("deleteAll") is not None else False, + "namespace": obj.get("namespace"), + "filter": obj.get("filter"), + } + ) + return _obj diff --git a/pinecone/core/client/models/describe_index_stats_request.py b/pinecone/core/client/models/describe_index_stats_request.py new file mode 100644 index 000000000..63a7e9b74 --- /dev/null +++ b/pinecone/core/client/models/describe_index_stats_request.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, Field + + +class DescribeIndexStatsRequest(BaseModel): + """ + The request for the `DescribeIndexStats` operation. # noqa: E501 + """ + + filter: Optional[Dict[str, Any]] = Field( + None, + description="If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.", + ) + __properties = ["filter"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> DescribeIndexStatsRequest: + """Create an instance of DescribeIndexStatsRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> DescribeIndexStatsRequest: + """Create an instance of DescribeIndexStatsRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return DescribeIndexStatsRequest.parse_obj(obj) + + _obj = DescribeIndexStatsRequest.parse_obj({"filter": obj.get("filter")}) + return _obj diff --git a/pinecone/core/client/models/describe_index_stats_response.py b/pinecone/core/client/models/describe_index_stats_response.py new file mode 100644 index 000000000..7a35ae470 --- /dev/null +++ b/pinecone/core/client/models/describe_index_stats_response.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Dict, Optional, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt +from pinecone.core.client.models.namespace_summary import NamespaceSummary + + +class DescribeIndexStatsResponse(BaseModel): + """ + The response for the `DescribeIndexStats` operation. # noqa: E501 + """ + + namespaces: Optional[Dict[str, NamespaceSummary]] = Field( + None, + description="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.", + ) + dimension: Optional[StrictInt] = Field(None, description="The dimension of the indexed vectors.") + index_fullness: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + alias="indexFullness", + description="The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%.", + ) + total_vector_count: Optional[StrictInt] = Field(None, alias="totalVectorCount") + __properties = ["namespaces", "dimension", "indexFullness", "totalVectorCount"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> DescribeIndexStatsResponse: + """Create an instance of DescribeIndexStatsResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each value in namespaces (dict) + _field_dict = {} + if self.namespaces: + for _key in self.namespaces: + if self.namespaces[_key]: + _field_dict[_key] = self.namespaces[_key].to_dict() + _dict["namespaces"] = _field_dict + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> DescribeIndexStatsResponse: + """Create an instance of DescribeIndexStatsResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return DescribeIndexStatsResponse.parse_obj(obj) + + _obj = DescribeIndexStatsResponse.parse_obj( + { + "namespaces": dict((_k, NamespaceSummary.from_dict(_v)) for _k, _v in obj.get("namespaces").items()) + if obj.get("namespaces") is not None + else None, + "dimension": obj.get("dimension"), + "index_fullness": obj.get("indexFullness"), + "total_vector_count": obj.get("totalVectorCount"), + } + ) + return _obj diff --git a/pinecone/core/client/models/fetch_response.py b/pinecone/core/client/models/fetch_response.py new file mode 100644 index 000000000..3763b572a --- /dev/null +++ b/pinecone/core/client/models/fetch_response.py @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Dict, Optional +from pydantic import BaseModel, Field, StrictStr +from pinecone.core.client.models.vector import Vector + + +class FetchResponse(BaseModel): + """ + The response for the `Fetch` operation. # noqa: E501 + """ + + vectors: Optional[Dict[str, Vector]] = None + namespace: Optional[StrictStr] = Field(None, description="The namespace of the vectors.") + __properties = ["vectors", "namespace"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> FetchResponse: + """Create an instance of FetchResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each value in vectors (dict) + _field_dict = {} + if self.vectors: + for _key in self.vectors: + if self.vectors[_key]: + _field_dict[_key] = self.vectors[_key].to_dict() + _dict["vectors"] = _field_dict + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> FetchResponse: + """Create an instance of FetchResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return FetchResponse.parse_obj(obj) + + _obj = FetchResponse.parse_obj( + { + "vectors": dict((_k, Vector.from_dict(_v)) for _k, _v in obj.get("vectors").items()) + if obj.get("vectors") is not None + else None, + "namespace": obj.get("namespace"), + } + ) + return _obj diff --git a/pinecone/core/client/models/hnsw_config.py b/pinecone/core/client/models/hnsw_config.py new file mode 100644 index 000000000..75b7d6ce6 --- /dev/null +++ b/pinecone/core/client/models/hnsw_config.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictInt + + +class HnswConfig(BaseModel): + """ + HnswConfig + """ + + ef_construction: Optional[StrictInt] = 500 + ef: Optional[StrictInt] = 250 + m: Optional[StrictInt] = Field(12, alias="M") + max_elements: Optional[StrictInt] = 50000000 + __properties = ["ef_construction", "ef", "M", "max_elements"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> HnswConfig: + """Create an instance of HnswConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> HnswConfig: + """Create an instance of HnswConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return HnswConfig.parse_obj(obj) + + _obj = HnswConfig.parse_obj( + { + "ef_construction": obj.get("ef_construction") if obj.get("ef_construction") is not None else 500, + "ef": obj.get("ef") if obj.get("ef") is not None else 250, + "m": obj.get("M") if obj.get("M") is not None else 12, + "max_elements": obj.get("max_elements") if obj.get("max_elements") is not None else 50000000, + } + ) + return _obj diff --git a/pinecone/core/client/models/index_meta.py b/pinecone/core/client/models/index_meta.py new file mode 100644 index 000000000..348cf509d --- /dev/null +++ b/pinecone/core/client/models/index_meta.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from pydantic import BaseModel, Field +from pinecone.core.client.models.index_meta_database import IndexMetaDatabase +from pinecone.core.client.models.index_meta_status import IndexMetaStatus + + +class IndexMeta(BaseModel): + """ + IndexMeta + """ + + database: IndexMetaDatabase = Field(...) + status: IndexMetaStatus = Field(...) + __properties = ["database", "status"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> IndexMeta: + """Create an instance of IndexMeta from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of database + if self.database: + _dict["database"] = self.database.to_dict() + # override the default output from pydantic by calling `to_dict()` of status + if self.status: + _dict["status"] = self.status.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> IndexMeta: + """Create an instance of IndexMeta from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return IndexMeta.parse_obj(obj) + + _obj = IndexMeta.parse_obj( + { + "database": IndexMetaDatabase.from_dict(obj.get("database")) + if obj.get("database") is not None + else None, + "status": IndexMetaStatus.from_dict(obj.get("status")) if obj.get("status") is not None else None, + } + ) + return _obj diff --git a/pinecone/core/client/models/index_meta_database.py b/pinecone/core/client/models/index_meta_database.py new file mode 100644 index 000000000..ba1af18eb --- /dev/null +++ b/pinecone/core/client/models/index_meta_database.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr +from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig + + +class IndexMetaDatabase(BaseModel): + """ + IndexMetaDatabase + """ + + name: StrictStr = Field(...) + dimension: StrictStr = Field(...) + capacity_mode: StrictStr = Field(...) + index_type: Optional[StrictStr] = None + metric: StrictStr = Field(...) + pods: Optional[StrictInt] = None + replicas: Optional[StrictInt] = None + shards: Optional[StrictInt] = None + pod_type: Optional[StrictStr] = None + index_config: Optional[IndexMetaDatabaseIndexConfig] = None + metadata_config: Optional[Dict[str, Any]] = None + __properties = [ + "name", + "dimension", + "capacity_mode", + "index_type", + "metric", + "pods", + "replicas", + "shards", + "pod_type", + "index_config", + "metadata_config", + ] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> IndexMetaDatabase: + """Create an instance of IndexMetaDatabase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of index_config + if self.index_config: + _dict["index_config"] = self.index_config.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> IndexMetaDatabase: + """Create an instance of IndexMetaDatabase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return IndexMetaDatabase.parse_obj(obj) + + _obj = IndexMetaDatabase.parse_obj( + { + "name": obj.get("name"), + "dimension": obj.get("dimension"), + "capacity_mode": obj.get("capacity_mode"), + "index_type": obj.get("index_type"), + "metric": obj.get("metric") if obj.get("metric") is not None else "cosine", + "pods": obj.get("pods"), + "replicas": obj.get("replicas"), + "shards": obj.get("shards"), + "pod_type": obj.get("pod_type"), + "index_config": IndexMetaDatabaseIndexConfig.from_dict(obj.get("index_config")) + if obj.get("index_config") is not None + else None, + "metadata_config": obj.get("metadata_config"), + } + ) + return _obj diff --git a/pinecone/core/client/models/index_meta_database_index_config.py b/pinecone/core/client/models/index_meta_database_index_config.py new file mode 100644 index 000000000..d58d078e9 --- /dev/null +++ b/pinecone/core/client/models/index_meta_database_index_config.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from pinecone.core.client.models.approximated_config import ApproximatedConfig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +INDEXMETADATABASEINDEXCONFIG_ONE_OF_SCHEMAS = ["ApproximatedConfig"] + + +class IndexMetaDatabaseIndexConfig(BaseModel): + """ + IndexMetaDatabaseIndexConfig + """ + + # data type: ApproximatedConfig + oneof_schema_1_validator: Optional[ApproximatedConfig] = None + if TYPE_CHECKING: + actual_instance: Union[ApproximatedConfig] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(INDEXMETADATABASEINDEXCONFIG_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator("actual_instance") + def actual_instance_must_validate_oneof(cls, v): + instance = IndexMetaDatabaseIndexConfig.construct() + error_messages = [] + match = 0 + # validate data type: ApproximatedConfig + if not isinstance(v, ApproximatedConfig): + error_messages.append(f"Error! Input type `{type(v)}` is not `ApproximatedConfig`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when setting `actual_instance` in IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when setting `actual_instance` in IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> IndexMetaDatabaseIndexConfig: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> IndexMetaDatabaseIndexConfig: + """Returns the object represented by the json string""" + instance = IndexMetaDatabaseIndexConfig.construct() + error_messages = [] + match = 0 + + # deserialize data into ApproximatedConfig + try: + instance.actual_instance = ApproximatedConfig.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when deserializing the JSON string into IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when deserializing the JSON string into IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " + + ", ".join(error_messages) + ) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) diff --git a/pinecone/core/client/models/index_meta_status.py b/pinecone/core/client/models/index_meta_status.py new file mode 100644 index 000000000..fc76025c9 --- /dev/null +++ b/pinecone/core/client/models/index_meta_status.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, validator + + +class IndexMetaStatus(BaseModel): + """ + IndexMetaStatus + """ + + ready: StrictBool = Field(...) + state: StrictStr = Field(...) + host: StrictStr = Field(...) + port: StrictInt = Field(...) + __properties = ["ready", "state", "host", "port"] + + @validator("state") + def state_validate_enum(cls, value): + """Validates the enum""" + if value not in ( + "Initializing", + "InitializationFailed", + "ScalingUp", + "ScalingDown", + "ScalingUpPodSize", + "ScalingDownPodSize", + "Terminating", + "Ready", + ): + raise ValueError( + "must be one of enum values ('Initializing', 'InitializationFailed', 'ScalingUp', 'ScalingDown', 'ScalingUpPodSize', 'ScalingDownPodSize', 'Terminating', 'Ready')" + ) + return value + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> IndexMetaStatus: + """Create an instance of IndexMetaStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> IndexMetaStatus: + """Create an instance of IndexMetaStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return IndexMetaStatus.parse_obj(obj) + + _obj = IndexMetaStatus.parse_obj( + {"ready": obj.get("ready"), "state": obj.get("state"), "host": obj.get("host"), "port": obj.get("port")} + ) + return _obj diff --git a/pinecone/core/client/models/list_indexes200_response.py b/pinecone/core/client/models/list_indexes200_response.py new file mode 100644 index 000000000..9a94ef226 --- /dev/null +++ b/pinecone/core/client/models/list_indexes200_response.py @@ -0,0 +1,82 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Optional +from pydantic import BaseModel, conlist +from pinecone.core.client.models.index_meta import IndexMeta + + +class ListIndexes200Response(BaseModel): + """ + ListIndexes200Response + """ + + databases: Optional[conlist(IndexMeta)] = None + __properties = ["databases"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ListIndexes200Response: + """Create an instance of ListIndexes200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in databases (list) + _items = [] + if self.databases: + for _item in self.databases: + if _item: + _items.append(_item.to_dict()) + _dict["databases"] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ListIndexes200Response: + """Create an instance of ListIndexes200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ListIndexes200Response.parse_obj(obj) + + _obj = ListIndexes200Response.parse_obj( + { + "databases": [IndexMeta.from_dict(_item) for _item in obj.get("databases")] + if obj.get("databases") is not None + else None + } + ) + return _obj diff --git a/pinecone/core/client/models/namespace_summary.py b/pinecone/core/client/models/namespace_summary.py new file mode 100644 index 000000000..8d5fb118d --- /dev/null +++ b/pinecone/core/client/models/namespace_summary.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictInt + + +class NamespaceSummary(BaseModel): + """ + A summary of the contents of a namespace. # noqa: E501 + """ + + vector_count: Optional[StrictInt] = Field( + None, + alias="vectorCount", + description="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.", + ) + __properties = ["vectorCount"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> NamespaceSummary: + """Create an instance of NamespaceSummary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> NamespaceSummary: + """Create an instance of NamespaceSummary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return NamespaceSummary.parse_obj(obj) + + _obj = NamespaceSummary.parse_obj({"vector_count": obj.get("vectorCount")}) + return _obj diff --git a/pinecone/core/client/models/patch_request.py b/pinecone/core/client/models/patch_request.py new file mode 100644 index 000000000..79ab8f29f --- /dev/null +++ b/pinecone/core/client/models/patch_request.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr + + +class PatchRequest(BaseModel): + """ + PatchRequest + """ + + replicas: Optional[StrictInt] = Field(None, description="The desired number of replicas for the index.") + pod_type: Optional[StrictStr] = Field( + None, + description="The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.", + ) + __properties = ["replicas", "pod_type"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> PatchRequest: + """Create an instance of PatchRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> PatchRequest: + """Create an instance of PatchRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PatchRequest.parse_obj(obj) + + _obj = PatchRequest.parse_obj({"replicas": obj.get("replicas"), "pod_type": obj.get("pod_type")}) + return _obj diff --git a/pinecone/core/client/models/protobuf_any.py b/pinecone/core/client/models/protobuf_any.py new file mode 100644 index 000000000..d1114da90 --- /dev/null +++ b/pinecone/core/client/models/protobuf_any.py @@ -0,0 +1,69 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional, Union +from pydantic import BaseModel, Field, StrictBytes, StrictStr + + +class ProtobufAny(BaseModel): + """ + ProtobufAny + """ + + type_url: Optional[StrictStr] = Field(None, alias="typeUrl") + value: Optional[Union[StrictBytes, StrictStr]] = None + __properties = ["typeUrl", "value"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ProtobufAny: + """Create an instance of ProtobufAny from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ProtobufAny: + """Create an instance of ProtobufAny from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ProtobufAny.parse_obj(obj) + + _obj = ProtobufAny.parse_obj({"type_url": obj.get("typeUrl"), "value": obj.get("value")}) + return _obj diff --git a/pinecone/core/client/models/protobuf_null_value.py b/pinecone/core/client/models/protobuf_null_value.py new file mode 100644 index 000000000..e90b5bd47 --- /dev/null +++ b/pinecone/core/client/models/protobuf_null_value.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import json +import pprint +import re # noqa: F401 +from aenum import Enum, no_arg + + +class ProtobufNullValue(str, Enum): + """ + `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value. + """ + + """ + allowed enum values + """ + NULL_VALUE = "NULL_VALUE" + + @classmethod + def from_json(cls, json_str: str) -> ProtobufNullValue: + """Create an instance of ProtobufNullValue from a JSON string""" + return ProtobufNullValue(json.loads(json_str)) diff --git a/pinecone/core/client/models/query_request.py b/pinecone/core/client/models/query_request.py new file mode 100644 index 000000000..19787a26b --- /dev/null +++ b/pinecone/core/client/models/query_request.py @@ -0,0 +1,134 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional, Union +from pydantic import BaseModel, Field, StrictBool, StrictFloat, StrictInt, StrictStr, conint, conlist, constr +from pinecone.core.client.models.query_vector import QueryVector +from pinecone.core.client.models.sparse_values import SparseValues + + +class QueryRequest(BaseModel): + """ + The request for the `Query` operation. # noqa: E501 + """ + + namespace: Optional[StrictStr] = Field(None, description="The namespace to query.") + top_k: conint(strict=True, le=10000, ge=1) = Field( + ..., alias="topK", description="The number of results to return for each query." + ) + filter: Optional[Dict[str, Any]] = Field( + None, + description="The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.", + ) + include_values: Optional[StrictBool] = Field( + False, alias="includeValues", description="Indicates whether vector values are included in the response." + ) + include_metadata: Optional[StrictBool] = Field( + False, + alias="includeMetadata", + description="Indicates whether metadata is included in the response as well as the ids.", + ) + queries: Optional[conlist(QueryVector)] = Field( + None, + description="DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.", + ) + vector: Optional[conlist(Union[StrictFloat, StrictInt])] = Field( + None, + description="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`.", + ) + sparse_vector: Optional[SparseValues] = Field(None, alias="sparseVector") + id: Optional[constr(strict=True, max_length=512)] = Field( + None, + description="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`.", + ) + __properties = [ + "namespace", + "topK", + "filter", + "includeValues", + "includeMetadata", + "queries", + "vector", + "sparseVector", + "id", + ] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> QueryRequest: + """Create an instance of QueryRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in queries (list) + _items = [] + if self.queries: + for _item in self.queries: + if _item: + _items.append(_item.to_dict()) + _dict["queries"] = _items + # override the default output from pydantic by calling `to_dict()` of sparse_vector + if self.sparse_vector: + _dict["sparseVector"] = self.sparse_vector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> QueryRequest: + """Create an instance of QueryRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return QueryRequest.parse_obj(obj) + + _obj = QueryRequest.parse_obj( + { + "namespace": obj.get("namespace"), + "top_k": obj.get("topK"), + "filter": obj.get("filter"), + "include_values": obj.get("includeValues") if obj.get("includeValues") is not None else False, + "include_metadata": obj.get("includeMetadata") if obj.get("includeMetadata") is not None else False, + "queries": [QueryVector.from_dict(_item) for _item in obj.get("queries")] + if obj.get("queries") is not None + else None, + "vector": obj.get("vector"), + "sparse_vector": SparseValues.from_dict(obj.get("sparseVector")) + if obj.get("sparseVector") is not None + else None, + "id": obj.get("id"), + } + ) + return _obj diff --git a/pinecone/core/client/models/query_response.py b/pinecone/core/client/models/query_response.py new file mode 100644 index 000000000..5c4f6bf27 --- /dev/null +++ b/pinecone/core/client/models/query_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Optional +from pydantic import BaseModel, Field, StrictStr, conlist +from pinecone.core.client.models.scored_vector import ScoredVector +from pinecone.core.client.models.single_query_results import SingleQueryResults + + +class QueryResponse(BaseModel): + """ + 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. # noqa: E501 + """ + + results: Optional[conlist(SingleQueryResults)] = Field( + None, description="DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`." + ) + matches: Optional[conlist(ScoredVector)] = Field(None, description="The matches for the vectors.") + namespace: Optional[StrictStr] = Field(None, description="The namespace for the vectors.") + __properties = ["results", "matches", "namespace"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> QueryResponse: + """Create an instance of QueryResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item in self.results: + if _item: + _items.append(_item.to_dict()) + _dict["results"] = _items + # override the default output from pydantic by calling `to_dict()` of each item in matches (list) + _items = [] + if self.matches: + for _item in self.matches: + if _item: + _items.append(_item.to_dict()) + _dict["matches"] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> QueryResponse: + """Create an instance of QueryResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return QueryResponse.parse_obj(obj) + + _obj = QueryResponse.parse_obj( + { + "results": [SingleQueryResults.from_dict(_item) for _item in obj.get("results")] + if obj.get("results") is not None + else None, + "matches": [ScoredVector.from_dict(_item) for _item in obj.get("matches")] + if obj.get("matches") is not None + else None, + "namespace": obj.get("namespace"), + } + ) + return _obj diff --git a/pinecone/core/client/models/query_vector.py b/pinecone/core/client/models/query_vector.py new file mode 100644 index 000000000..544bc6fd5 --- /dev/null +++ b/pinecone/core/client/models/query_vector.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr, conint, conlist +from pinecone.core.client.models.sparse_values import SparseValues + + +class QueryVector(BaseModel): + """ + A single query vector within a `QueryRequest`. # noqa: E501 + """ + + values: conlist(Union[StrictFloat, StrictInt]) = Field( + ..., + description="The query vector values. This should be the same length as the dimension of the index being queried.", + ) + sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") + top_k: Optional[conint(strict=True, le=10000, ge=1)] = Field( + None, alias="topK", description="An override for the number of results to return for this query vector." + ) + namespace: Optional[StrictStr] = Field(None, description="An override the namespace to search.") + filter: Optional[Dict[str, Any]] = Field( + None, description="An override for the metadata filter to apply. This replaces the request-level filter." + ) + __properties = ["values", "sparseValues", "topK", "namespace", "filter"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> QueryVector: + """Create an instance of QueryVector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of sparse_values + if self.sparse_values: + _dict["sparseValues"] = self.sparse_values.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> QueryVector: + """Create an instance of QueryVector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return QueryVector.parse_obj(obj) + + _obj = QueryVector.parse_obj( + { + "values": obj.get("values"), + "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) + if obj.get("sparseValues") is not None + else None, + "top_k": obj.get("topK"), + "namespace": obj.get("namespace"), + "filter": obj.get("filter"), + } + ) + return _obj diff --git a/pinecone/core/client/models/rpc_status.py b/pinecone/core/client/models/rpc_status.py new file mode 100644 index 000000000..e02eadb6c --- /dev/null +++ b/pinecone/core/client/models/rpc_status.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Optional +from pydantic import BaseModel, StrictInt, StrictStr, conlist +from pinecone.core.client.models.protobuf_any import ProtobufAny + + +class RpcStatus(BaseModel): + """ + RpcStatus + """ + + code: Optional[StrictInt] = None + message: Optional[StrictStr] = None + details: Optional[conlist(ProtobufAny)] = None + __properties = ["code", "message", "details"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RpcStatus: + """Create an instance of RpcStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in details (list) + _items = [] + if self.details: + for _item in self.details: + if _item: + _items.append(_item.to_dict()) + _dict["details"] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RpcStatus: + """Create an instance of RpcStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RpcStatus.parse_obj(obj) + + _obj = RpcStatus.parse_obj( + { + "code": obj.get("code"), + "message": obj.get("message"), + "details": [ProtobufAny.from_dict(_item) for _item in obj.get("details")] + if obj.get("details") is not None + else None, + } + ) + return _obj diff --git a/pinecone/core/client/models/scored_vector.py b/pinecone/core/client/models/scored_vector.py new file mode 100644 index 000000000..bf983eae6 --- /dev/null +++ b/pinecone/core/client/models/scored_vector.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist, constr +from pinecone.core.client.models.sparse_values import SparseValues + + +class ScoredVector(BaseModel): + """ + ScoredVector + """ + + id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="This is the vector's unique id.") + score: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + description="This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.", + ) + values: Optional[conlist(Union[StrictFloat, StrictInt])] = Field( + None, description="This is the vector data, if it is requested." + ) + sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") + metadata: Optional[Dict[str, Any]] = Field(None, description="This is the metadata, if it is requested.") + __properties = ["id", "score", "values", "sparseValues", "metadata"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ScoredVector: + """Create an instance of ScoredVector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of sparse_values + if self.sparse_values: + _dict["sparseValues"] = self.sparse_values.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ScoredVector: + """Create an instance of ScoredVector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ScoredVector.parse_obj(obj) + + _obj = ScoredVector.parse_obj( + { + "id": obj.get("id"), + "score": obj.get("score"), + "values": obj.get("values"), + "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) + if obj.get("sparseValues") is not None + else None, + "metadata": obj.get("metadata"), + } + ) + return _obj diff --git a/pinecone/core/client/models/single_query_results.py b/pinecone/core/client/models/single_query_results.py new file mode 100644 index 000000000..91ef3c00b --- /dev/null +++ b/pinecone/core/client/models/single_query_results.py @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Optional +from pydantic import BaseModel, Field, StrictStr, conlist +from pinecone.core.client.models.scored_vector import ScoredVector + + +class SingleQueryResults(BaseModel): + """ + SingleQueryResults + """ + + matches: Optional[conlist(ScoredVector)] = Field(None, description="The matches for the vectors.") + namespace: Optional[StrictStr] = Field(None, description="The namespace for the vectors.") + __properties = ["matches", "namespace"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> SingleQueryResults: + """Create an instance of SingleQueryResults from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in matches (list) + _items = [] + if self.matches: + for _item in self.matches: + if _item: + _items.append(_item.to_dict()) + _dict["matches"] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> SingleQueryResults: + """Create an instance of SingleQueryResults from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return SingleQueryResults.parse_obj(obj) + + _obj = SingleQueryResults.parse_obj( + { + "matches": [ScoredVector.from_dict(_item) for _item in obj.get("matches")] + if obj.get("matches") is not None + else None, + "namespace": obj.get("namespace"), + } + ) + return _obj diff --git a/pinecone/core/client/models/sparse_values.py b/pinecone/core/client/models/sparse_values.py new file mode 100644 index 000000000..c72173d33 --- /dev/null +++ b/pinecone/core/client/models/sparse_values.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist + + +class SparseValues(BaseModel): + """ + Vector sparse data. Represented as a list of indices and a list of corresponded values, which must be with the same length. # noqa: E501 + """ + + indices: conlist(StrictInt) = Field(..., description="The indices of the sparse data.") + values: conlist(Union[StrictFloat, StrictInt]) = Field( + ..., + description="The corresponding values of the sparse data, which must be with the same length as the indices.", + ) + __properties = ["indices", "values"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> SparseValues: + """Create an instance of SparseValues from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> SparseValues: + """Create an instance of SparseValues from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return SparseValues.parse_obj(obj) + + _obj = SparseValues.parse_obj({"indices": obj.get("indices"), "values": obj.get("values")}) + return _obj diff --git a/pinecone/core/client/models/update_request.py b/pinecone/core/client/models/update_request.py new file mode 100644 index 000000000..a04a39208 --- /dev/null +++ b/pinecone/core/client/models/update_request.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr, conlist, constr +from pinecone.core.client.models.sparse_values import SparseValues + + +class UpdateRequest(BaseModel): + """ + The request for the `Upsert` operation. # noqa: E501 + """ + + id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="Vector's unique id.") + values: Optional[conlist(Union[StrictFloat, StrictInt])] = Field(None, description="Vector data.") + sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") + set_metadata: Optional[Dict[str, Any]] = Field( + None, alias="setMetadata", description="Metadata to *set* for the vector." + ) + namespace: Optional[StrictStr] = Field(None, description="Namespace name where to update the vector.") + __properties = ["id", "values", "sparseValues", "setMetadata", "namespace"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UpdateRequest: + """Create an instance of UpdateRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of sparse_values + if self.sparse_values: + _dict["sparseValues"] = self.sparse_values.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UpdateRequest: + """Create an instance of UpdateRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UpdateRequest.parse_obj(obj) + + _obj = UpdateRequest.parse_obj( + { + "id": obj.get("id"), + "values": obj.get("values"), + "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) + if obj.get("sparseValues") is not None + else None, + "set_metadata": obj.get("setMetadata"), + "namespace": obj.get("namespace"), + } + ) + return _obj diff --git a/pinecone/core/client/models/upsert_request.py b/pinecone/core/client/models/upsert_request.py new file mode 100644 index 000000000..11518db50 --- /dev/null +++ b/pinecone/core/client/models/upsert_request.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List, Optional +from pydantic import BaseModel, Field, StrictStr, conlist +from pinecone.core.client.models.vector import Vector + + +class UpsertRequest(BaseModel): + """ + The request for the `Upsert` operation. # noqa: E501 + """ + + vectors: conlist(Vector) = Field( + ..., description="An array containing the vectors to upsert. Recommended batch limit is 100 vectors." + ) + namespace: Optional[StrictStr] = Field(None, description="This is the namespace name where you upsert vectors.") + __properties = ["vectors", "namespace"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UpsertRequest: + """Create an instance of UpsertRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in vectors (list) + _items = [] + if self.vectors: + for _item in self.vectors: + if _item: + _items.append(_item.to_dict()) + _dict["vectors"] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UpsertRequest: + """Create an instance of UpsertRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UpsertRequest.parse_obj(obj) + + _obj = UpsertRequest.parse_obj( + { + "vectors": [Vector.from_dict(_item) for _item in obj.get("vectors")] + if obj.get("vectors") is not None + else None, + "namespace": obj.get("namespace"), + } + ) + return _obj diff --git a/pinecone/core/client/models/upsert_response.py b/pinecone/core/client/models/upsert_response.py new file mode 100644 index 000000000..cd17799e4 --- /dev/null +++ b/pinecone/core/client/models/upsert_response.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictInt + + +class UpsertResponse(BaseModel): + """ + The response for the `Upsert` operation. # noqa: E501 + """ + + upserted_count: Optional[StrictInt] = Field( + None, alias="upsertedCount", description="The number of vectors upserted." + ) + __properties = ["upsertedCount"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UpsertResponse: + """Create an instance of UpsertResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UpsertResponse: + """Create an instance of UpsertResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UpsertResponse.parse_obj(obj) + + _obj = UpsertResponse.parse_obj({"upserted_count": obj.get("upsertedCount")}) + return _obj diff --git a/pinecone/core/client/models/vector.py b/pinecone/core/client/models/vector.py new file mode 100644 index 000000000..963751811 --- /dev/null +++ b/pinecone/core/client/models/vector.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, List, Optional, Union +from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist, constr +from pinecone.core.client.models.sparse_values import SparseValues + + +class Vector(BaseModel): + """ + Vector + """ + + id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="This is the vector's unique id.") + values: conlist(Union[StrictFloat, StrictInt]) = Field( + ..., description="This is the vector data included in the request." + ) + sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") + metadata: Optional[Dict[str, Any]] = Field(None, description="This is the metadata included in the request.") + __properties = ["id", "values", "sparseValues", "metadata"] + + class Config: + """Pydantic configuration""" + + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Vector: + """Create an instance of Vector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of sparse_values + if self.sparse_values: + _dict["sparseValues"] = self.sparse_values.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Vector: + """Create an instance of Vector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Vector.parse_obj(obj) + + _obj = Vector.parse_obj( + { + "id": obj.get("id"), + "values": obj.get("values"), + "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) + if obj.get("sparseValues") is not None + else None, + "metadata": obj.get("metadata"), + } + ) + return _obj diff --git a/pinecone/core/client/py.typed b/pinecone/core/client/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index b986712be..4cbc0c0d0 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -1,12 +1,16 @@ +# coding: utf-8 + """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 import io @@ -14,8 +18,8 @@ import logging import re import ssl -from urllib.parse import urlencode +from urllib.parse import urlencode, quote_plus import urllib3 from pinecone.core.client.exceptions import ( @@ -25,6 +29,7 @@ NotFoundException, ServiceException, ApiValueError, + BadRequestException, ) @@ -32,7 +37,7 @@ class RESTResponse(io.IOBase): - def __init__(self, resp): + def __init__(self, resp) -> None: self.urllib3_response = resp self.status = resp.status self.reason = resp.reason @@ -47,8 +52,8 @@ def getheader(self, name, default=None): return self.urllib3_response.headers.get(name, default) -class RESTClientObject(object): - def __init__(self, configuration, pools_size=4, maxsize=None): +class RESTClientObject: + def __init__(self, configuration, pools_size=4, maxsize=None) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 @@ -68,6 +73,9 @@ def __init__(self, configuration, pools_size=4, maxsize=None): if configuration.retries is not None: addition_pool_args["retries"] = configuration.retries + if configuration.tls_server_name: + addition_pool_args["server_hostname"] = configuration.tls_server_name + if configuration.socket_options is not None: addition_pool_args["socket_options"] = configuration.socket_options @@ -88,7 +96,7 @@ def __init__(self, configuration, pools_size=4, maxsize=None): key_file=configuration.key_file, proxy_url=configuration.proxy, proxy_headers=configuration.proxy_headers, - **addition_pool_args + **addition_pool_args, ) else: self.pool_manager = urllib3.PoolManager( @@ -98,7 +106,7 @@ def __init__(self, configuration, pools_size=4, maxsize=None): ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, - **addition_pool_args + **addition_pool_args, ) def request( @@ -138,6 +146,9 @@ def request( post_params = post_params or {} headers = headers or {} + # url already contains the URL query string + # so reset query_params to empty dict + query_params = {} timeout = None if _request_timeout: @@ -149,12 +160,8 @@ def request( try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: - # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests - if (method != "DELETE") and ("Content-Type" not in headers): - headers["Content-Type"] = "application/json" - if query_params: - url += "?" + urlencode(query_params) - if ("Content-Type" not in headers) or (re.search("json", headers["Content-Type"], re.IGNORECASE)): + # no content type provided or payload is json + if not headers.get("Content-Type") or re.search("json", headers["Content-Type"], re.IGNORECASE): request_body = None if body is not None: request_body = json.dumps(body) @@ -212,7 +219,7 @@ def request( # For `GET`, `HEAD` else: r = self.pool_manager.request( - method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers + method, url, fields={}, preload_content=_preload_content, timeout=timeout, headers=headers ) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) @@ -225,6 +232,9 @@ def request( logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: + if r.status == 400: + raise BadRequestException(http_resp=r) + if r.status == 401: raise UnauthorizedException(http_resp=r) @@ -241,7 +251,7 @@ def request( return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def get_request(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request( "GET", url, @@ -251,7 +261,7 @@ def GET(self, url, headers=None, query_params=None, _preload_content=True, _requ query_params=query_params, ) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): + def head_request(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request( "HEAD", url, @@ -261,7 +271,7 @@ def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _req query_params=query_params, ) - def OPTIONS( + def options_request( self, url, headers=None, @@ -282,7 +292,9 @@ def OPTIONS( body=body, ) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): + def delete_request( + self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None + ): return self.request( "DELETE", url, @@ -293,7 +305,7 @@ def DELETE(self, url, headers=None, query_params=None, body=None, _preload_conte body=body, ) - def POST( + def post_request( self, url, headers=None, @@ -314,7 +326,7 @@ def POST( body=body, ) - def PUT( + def put_request( self, url, headers=None, @@ -335,7 +347,7 @@ def PUT( body=body, ) - def PATCH( + def patch_request( self, url, headers=None, diff --git a/pinecone/core/exceptions.py b/pinecone/core/exceptions.py deleted file mode 100644 index cd4577726..000000000 --- a/pinecone/core/exceptions.py +++ /dev/null @@ -1,6 +0,0 @@ -class PineconeException(Exception): - """The base exception class for all Pinecone client exceptions.""" - - -class PineconeProtocolError(PineconeException): - """Raised when something unexpected happens mid-request/response.""" diff --git a/pinecone/core/grpc/__init__.py b/pinecone/core/grpc/__init__.py deleted file mode 100644 index 8b1378917..000000000 --- a/pinecone/core/grpc/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pinecone/core/grpc/protos/__init__.py b/pinecone/core/grpc/protos/__init__.py deleted file mode 100644 index 8b1378917..000000000 --- a/pinecone/core/grpc/protos/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pinecone/exceptions.py b/pinecone/exceptions.py index ce23887f0..62da708f7 100644 --- a/pinecone/exceptions.py +++ b/pinecone/exceptions.py @@ -1,4 +1,3 @@ -from .core.exceptions import PineconeException, PineconeProtocolError from .core.client.exceptions import ( OpenApiException, ApiAttributeError, @@ -12,6 +11,12 @@ ServiceException, ) +class PineconeException(Exception): + """The base exception class for all Pinecone client exceptions.""" + +class PineconeProtocolError(PineconeException): + """Raised when something unexpected happens mid-request/response.""" + __all__ = [ "PineconeException", "PineconeProtocolError", diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py similarity index 98% rename from pinecone/core/grpc/index_grpc.py rename to pinecone/grpc/index_grpc.py index f62e9ec8a..1e35300ba 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -15,8 +15,8 @@ from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, DescribeIndexStatsResponse from pinecone.config import Config -from pinecone.core.client.model.namespace_summary import NamespaceSummary -from pinecone.core.client.model.vector import Vector as _Vector +from pinecone.core.client.models.namespace_summary import NamespaceSummary +from pinecone.core.client.models.vector import Vector as _Vector from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector as GRPCVector, QueryVector as GRPCQueryVector, @@ -31,11 +31,11 @@ UpdateResponse, SparseValues as GRPCSparseValues, ) -from pinecone.core.client.model.sparse_values import SparseValues +from pinecone.core.client.models.sparse_values import SparseValues from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub -from pinecone.core.grpc.retry import RetryOnRpcErrorClientInterceptor, RetryConfig -from pinecone.core.utils import _generate_request_id, dict_to_proto_struct, fix_tuple_length -from pinecone.core.utils.constants import ( +from pinecone.grpc.retry import RetryOnRpcErrorClientInterceptor, RetryConfig +from pinecone.utils import _generate_request_id, dict_to_proto_struct, fix_tuple_length +from pinecone.utils.constants import ( MAX_MSG_SIZE, REQUEST_ID, CLIENT_VERSION, @@ -349,7 +349,7 @@ def upsert( namespace: Optional[str] = None, batch_size: Optional[int] = None, show_progress: bool = True, - **kwargs + **kwargs, ) -> Union[UpsertResponse, PineconeGrpcFuture]: """ The upsert operation writes vectors into a namespace. @@ -565,7 +565,7 @@ def delete( namespace: Optional[str] = None, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, async_req: bool = False, - **kwargs + **kwargs, ) -> Union[DeleteResponse, PineconeGrpcFuture]: """ The Delete operation deletes vectors from the index, from a single namespace. @@ -650,7 +650,7 @@ def query( include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, sparse_vector: Optional[Union[GRPCSparseValues, Dict[str, Union[List[float], List[int]]]]] = None, - **kwargs + **kwargs, ) -> QueryResponse: """ The Query operation searches a namespace, using a query vector. @@ -740,7 +740,7 @@ def update( set_metadata: Optional[Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, namespace: Optional[str] = None, sparse_values: Optional[Union[GRPCSparseValues, Dict[str, Union[List[float], List[int]]]]] = None, - **kwargs + **kwargs, ) -> Union[UpdateResponse, PineconeGrpcFuture]: """ The Update operation updates vector in a namespace. @@ -840,4 +840,4 @@ def _parse_sparse_values_arg( f"Received: {sparse_values}" ) - return GRPCSparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) + return GRPCSparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) \ No newline at end of file diff --git a/pinecone/core/grpc/protos/vector_column_service_pb2.py b/pinecone/grpc/protos/vector_column_service_pb2.py similarity index 99% rename from pinecone/core/grpc/protos/vector_column_service_pb2.py rename to pinecone/grpc/protos/vector_column_service_pb2.py index 1b4ebadc1..cab350a61 100644 --- a/pinecone/core/grpc/protos/vector_column_service_pb2.py +++ b/pinecone/grpc/protos/vector_column_service_pb2.py @@ -1290,4 +1290,4 @@ DESCRIPTOR.services_by_name["VectorColumnService"] = _VECTORCOLUMNSERVICE -# @@protoc_insertion_point(module_scope) +# @@protoc_insertion_point(module_scope) \ No newline at end of file diff --git a/pinecone/core/grpc/protos/vector_column_service_pb2.pyi b/pinecone/grpc/protos/vector_column_service_pb2.pyi similarity index 99% rename from pinecone/core/grpc/protos/vector_column_service_pb2.pyi rename to pinecone/grpc/protos/vector_column_service_pb2.pyi index 3b85ddb13..3b0176f67 100644 --- a/pinecone/core/grpc/protos/vector_column_service_pb2.pyi +++ b/pinecone/grpc/protos/vector_column_service_pb2.pyi @@ -347,4 +347,4 @@ class DescribeIndexStatsResponse(google___protobuf___message___Message): self, field_name: typing_extensions___Literal["dimension", b"dimension", "namespaces", b"namespaces"] ) -> None: ... -type___DescribeIndexStatsResponse = DescribeIndexStatsResponse +type___DescribeIndexStatsResponse = DescribeIndexStatsResponse \ No newline at end of file diff --git a/pinecone/core/grpc/protos/vector_column_service_pb2_grpc.py b/pinecone/grpc/protos/vector_column_service_pb2_grpc.py similarity index 99% rename from pinecone/core/grpc/protos/vector_column_service_pb2_grpc.py rename to pinecone/grpc/protos/vector_column_service_pb2_grpc.py index 677e12b4b..93db50203 100644 --- a/pinecone/core/grpc/protos/vector_column_service_pb2_grpc.py +++ b/pinecone/grpc/protos/vector_column_service_pb2_grpc.py @@ -264,4 +264,4 @@ def DescribeIndexStats( wait_for_ready, timeout, metadata, - ) + ) \ No newline at end of file diff --git a/pinecone/core/grpc/retry.py b/pinecone/grpc/retry.py similarity index 99% rename from pinecone/core/grpc/retry.py rename to pinecone/grpc/retry.py index b27182884..e1ec306a3 100644 --- a/pinecone/core/grpc/retry.py +++ b/pinecone/grpc/retry.py @@ -84,4 +84,4 @@ class RetryConfig(NamedTuple): max_attempts: int = 4 sleep_policy: SleepPolicy = ExponentialBackoff(init_backoff_ms=100, max_backoff_ms=1600, multiplier=2) - retryable_status: Optional[Tuple[grpc.StatusCode, ...]] = (grpc.StatusCode.UNAVAILABLE,) + retryable_status: Optional[Tuple[grpc.StatusCode, ...]] = (grpc.StatusCode.UNAVAILABLE,) \ No newline at end of file diff --git a/pinecone/index.py b/pinecone/index.py index 64d66d676..663645d6f 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -6,7 +6,7 @@ from collections.abc import Iterable, Mapping from typing import Union, List, Tuple, Optional, Dict, Any -from .core.client.model.sparse_values import SparseValues +from .core.client.models.sparse_values import SparseValues from pinecone import Config from pinecone.core.client import ApiClient from .core.client.models import ( @@ -28,7 +28,7 @@ DescribeIndexStatsRequest, ) from pinecone.core.client.api.vector_operations_api import VectorOperationsApi -from pinecone.core.utils import fix_tuple_length, get_user_agent, warn_deprecated +from .utils import fix_tuple_length, get_user_agent, warn_deprecated import copy __all__ = [ @@ -52,8 +52,8 @@ "SparseValues", ] -from .core.utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS -from .core.utils.error_handling import validate_and_convert_errors +from .utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS +from .utils.error_handling import validate_and_convert_errors _OPENAPI_ENDPOINT_PARAMS = ( "_return_http_data_only", @@ -68,10 +68,10 @@ def parse_query_response(response: QueryResponse, unary_query: bool): if unary_query: - response._data_store.pop("results", None) + response.results = None else: - response._data_store.pop("matches", None) - response._data_store.pop("namespace", None) + response.matches = None + response.namespace = None return response diff --git a/pinecone/info.py b/pinecone/info.py deleted file mode 100644 index 36f5ae2ed..000000000 --- a/pinecone/info.py +++ /dev/null @@ -1,35 +0,0 @@ -from pinecone.core.api_action import ActionAPI, VersionResponse, WhoAmIResponse -from pinecone.config import Config - -import time -import requests - -__all__ = ["version", "whoami", "VersionResponse", "WhoAmIResponse"] - - -def _get_action_api(): - return ActionAPI(host=Config.CONTROLLER_HOST, api_key=Config.API_KEY) - - -def version() -> VersionResponse: - """Returns version information (client and server).""" - api = _get_action_api() - return api.version() - - -def whoami() -> WhoAmIResponse: - """Returns the details of the currently authenticated API key.""" - api = _get_action_api() - return api.whoami() - - -def wait_controller_ready(timeout: int = 30): - connection = False - max_time = time.time() + timeout - while (not connection) and time.time() < max_time: - try: - version() - time.sleep(3) - connection = True - except requests.exceptions.ConnectionError: - time.sleep(1) diff --git a/pinecone/manage.py b/pinecone/manage.py index 76541edf7..5f3227a8f 100644 --- a/pinecone/manage.py +++ b/pinecone/manage.py @@ -5,10 +5,10 @@ from pinecone.config import Config from pinecone.core.client.api.index_operations_api import IndexOperationsApi from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.model.create_request import CreateRequest -from pinecone.core.client.model.patch_request import PatchRequest -from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.utils import get_user_agent +from pinecone.core.client.models.create_request import CreateRequest +from pinecone.core.client.models.patch_request import PatchRequest +from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.utils import get_user_agent __all__ = [ "create_index", @@ -73,6 +73,9 @@ def _get_status(name: str): def create_index( name: str, dimension: int, + cloud: str, + region: str, + capacity_mode: str, timeout: int = None, index_type: str = "approximated", metric: str = "cosine", @@ -89,6 +92,9 @@ def create_index( :param name: the name of the index. :type name: str :param dimension: the dimension of vectors that would be inserted in the index + :param cloud: The cloud where you would like your index hosted. One of `{"aws", "gcp"}`. + :param region: The region where you would like your index hosted. + :param capacity_mode: The capacity mode for the index. One of `{"pod"}`. :param index_type: type of index, one of `{"approximated", "exact"}`, defaults to "approximated". The "approximated" index uses fast approximate search algorithms developed by Pinecone. The "exact" index uses accurate exact search algorithms. @@ -125,6 +131,9 @@ def create_index( create_request=CreateRequest( name=name, dimension=dimension, + cloud=cloud, + region=region, + capacity_mode=capacity_mode, index_type=index_type, metric=metric, replicas=replicas, diff --git a/pinecone/core/utils/__init__.py b/pinecone/utils/__init__.py similarity index 93% rename from pinecone/core/utils/__init__.py rename to pinecone/utils/__init__.py index d4cca1643..08f885ebf 100644 --- a/pinecone/core/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -10,7 +10,7 @@ import urllib3 try: - from pinecone.core.grpc.protos import vector_column_service_pb2 + from pinecone.grpc.protos import vector_column_service_pb2 from google.protobuf.struct_pb2 import Struct from google.protobuf import json_format import numpy as np @@ -51,11 +51,11 @@ def dump_strings_public(strs: List[str], compressed: bool = False) -> "vector_co def get_version(): - return Path(__file__).parent.parent.parent.joinpath("__version__").read_text().strip() + return Path(__file__).parent.parent.joinpath("__version__").read_text().strip() def get_environment(): - return Path(__file__).parent.parent.parent.joinpath("__environment__").read_text().strip() + return Path(__file__).parent.parent.joinpath("__environment__").read_text().strip() def validate_dns_name(name): @@ -133,4 +133,4 @@ def check_kwargs(caller, given): argspec = inspect.getfullargspec(caller) diff = set(given).difference(argspec.args) if diff: - logging.exception(caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), exc_info=False) + logging.exception(caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), exc_info=False) \ No newline at end of file diff --git a/pinecone/core/utils/constants.py b/pinecone/utils/constants.py similarity index 87% rename from pinecone/core/utils/constants.py rename to pinecone/utils/constants.py index ca9d96310..c415a36a6 100644 --- a/pinecone/core/utils/constants.py +++ b/pinecone/utils/constants.py @@ -1,7 +1,7 @@ import os import enum -from pinecone.core.utils import get_environment, get_version +from pinecone.utils import get_environment, get_version PARENT_LOGGER_NAME = "pinecone" DEFAULT_PARENT_LOGGER_LEVEL = "ERROR" @@ -35,4 +35,4 @@ class NodeType(str, enum.Enum): TCP_KEEPCNT = 4 REQUIRED_VECTOR_FIELDS = {"id", "values"} -OPTIONAL_VECTOR_FIELDS = {"sparse_values", "metadata"} +OPTIONAL_VECTOR_FIELDS = {"sparse_values", "metadata"} \ No newline at end of file diff --git a/pinecone/core/utils/error_handling.py b/pinecone/utils/error_handling.py similarity index 75% rename from pinecone/core/utils/error_handling.py rename to pinecone/utils/error_handling.py index 6d3f54054..f64b1a59d 100644 --- a/pinecone/core/utils/error_handling.py +++ b/pinecone/utils/error_handling.py @@ -3,8 +3,7 @@ from urllib3.exceptions import MaxRetryError, ProtocolError -from pinecone import Config, PineconeProtocolError - +from pinecone import Config def validate_and_convert_errors(func): @wraps(func) @@ -14,15 +13,15 @@ def inner_func(*args, **kwargs): return func(*args, **kwargs) except MaxRetryError as e: if isinstance(e.reason, ProtocolError): - raise PineconeProtocolError( + raise ProtocolError( f"Failed to connect to {e.url}; did you specify the correct index name?" ) from e else: raise except ProtocolError as e: - raise PineconeProtocolError(f"Failed to connect; did you specify the correct index name?") from e + raise ProtocolError(f"Failed to connect; did you specify the correct index name?") from e # Override signature sig = inspect.signature(func) inner_func.__signature__ = sig - return inner_func + return inner_func \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index 0daffa1cc..1060d39a9 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,5 +1,17 @@ # This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. +[[package]] +name = "aenum" +version = "3.1.11" +description = "Advanced Enumerations (compatible with Python's stdlib Enum), NamedTuples, and NamedConstants" +optional = false +python-versions = "*" +files = [ + {file = "aenum-3.1.11-py2-none-any.whl", hash = "sha256:525b4870a27d0b471c265bda692bc657f1e0dd7597ad4186d072c59f9db666f6"}, + {file = "aenum-3.1.11-py3-none-any.whl", hash = "sha256:12ae89967f2e25c0ce28c293955d643f891603488bc3d9946158ba2b35203638"}, + {file = "aenum-3.1.11.tar.gz", hash = "sha256:aed2c273547ae72a0d5ee869719c02a643da16bf507c80958faadc7e038e3f73"}, +] + [[package]] name = "astunparse" version = "1.6.3" @@ -695,6 +707,58 @@ files = [ {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, ] +[[package]] +name = "pydantic" +version = "1.10.12" +description = "Data validation and settings management using python type hints" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic-1.10.12-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a1fcb59f2f355ec350073af41d927bf83a63b50e640f4dbaa01053a28b7a7718"}, + {file = "pydantic-1.10.12-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b7ccf02d7eb340b216ec33e53a3a629856afe1c6e0ef91d84a4e6f2fb2ca70fe"}, + {file = "pydantic-1.10.12-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8fb2aa3ab3728d950bcc885a2e9eff6c8fc40bc0b7bb434e555c215491bcf48b"}, + {file = "pydantic-1.10.12-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:771735dc43cf8383959dc9b90aa281f0b6092321ca98677c5fb6125a6f56d58d"}, + {file = "pydantic-1.10.12-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:ca48477862372ac3770969b9d75f1bf66131d386dba79506c46d75e6b48c1e09"}, + {file = "pydantic-1.10.12-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:a5e7add47a5b5a40c49b3036d464e3c7802f8ae0d1e66035ea16aa5b7a3923ed"}, + {file = "pydantic-1.10.12-cp310-cp310-win_amd64.whl", hash = "sha256:e4129b528c6baa99a429f97ce733fff478ec955513630e61b49804b6cf9b224a"}, + {file = "pydantic-1.10.12-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b0d191db0f92dfcb1dec210ca244fdae5cbe918c6050b342d619c09d31eea0cc"}, + {file = "pydantic-1.10.12-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:795e34e6cc065f8f498c89b894a3c6da294a936ee71e644e4bd44de048af1405"}, + {file = "pydantic-1.10.12-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:69328e15cfda2c392da4e713443c7dbffa1505bc9d566e71e55abe14c97ddc62"}, + {file = "pydantic-1.10.12-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2031de0967c279df0d8a1c72b4ffc411ecd06bac607a212892757db7462fc494"}, + {file = "pydantic-1.10.12-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:ba5b2e6fe6ca2b7e013398bc7d7b170e21cce322d266ffcd57cca313e54fb246"}, + {file = "pydantic-1.10.12-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:2a7bac939fa326db1ab741c9d7f44c565a1d1e80908b3797f7f81a4f86bc8d33"}, + {file = "pydantic-1.10.12-cp311-cp311-win_amd64.whl", hash = "sha256:87afda5539d5140cb8ba9e8b8c8865cb5b1463924d38490d73d3ccfd80896b3f"}, + {file = "pydantic-1.10.12-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:549a8e3d81df0a85226963611950b12d2d334f214436a19537b2efed61b7639a"}, + {file = "pydantic-1.10.12-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598da88dfa127b666852bef6d0d796573a8cf5009ffd62104094a4fe39599565"}, + {file = "pydantic-1.10.12-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba5c4a8552bff16c61882db58544116d021d0b31ee7c66958d14cf386a5b5350"}, + {file = "pydantic-1.10.12-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:c79e6a11a07da7374f46970410b41d5e266f7f38f6a17a9c4823db80dadf4303"}, + {file = "pydantic-1.10.12-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:ab26038b8375581dc832a63c948f261ae0aa21f1d34c1293469f135fa92972a5"}, + {file = "pydantic-1.10.12-cp37-cp37m-win_amd64.whl", hash = "sha256:e0a16d274b588767602b7646fa05af2782576a6cf1022f4ba74cbb4db66f6ca8"}, + {file = "pydantic-1.10.12-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6a9dfa722316f4acf4460afdf5d41d5246a80e249c7ff475c43a3a1e9d75cf62"}, + {file = "pydantic-1.10.12-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:a73f489aebd0c2121ed974054cb2759af8a9f747de120acd2c3394cf84176ccb"}, + {file = "pydantic-1.10.12-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b30bcb8cbfccfcf02acb8f1a261143fab622831d9c0989707e0e659f77a18e0"}, + {file = "pydantic-1.10.12-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2fcfb5296d7877af406ba1547dfde9943b1256d8928732267e2653c26938cd9c"}, + {file = "pydantic-1.10.12-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:2f9a6fab5f82ada41d56b0602606a5506aab165ca54e52bc4545028382ef1c5d"}, + {file = "pydantic-1.10.12-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:dea7adcc33d5d105896401a1f37d56b47d443a2b2605ff8a969a0ed5543f7e33"}, + {file = "pydantic-1.10.12-cp38-cp38-win_amd64.whl", hash = "sha256:1eb2085c13bce1612da8537b2d90f549c8cbb05c67e8f22854e201bde5d98a47"}, + {file = "pydantic-1.10.12-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ef6c96b2baa2100ec91a4b428f80d8f28a3c9e53568219b6c298c1125572ebc6"}, + {file = "pydantic-1.10.12-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6c076be61cd0177a8433c0adcb03475baf4ee91edf5a4e550161ad57fc90f523"}, + {file = "pydantic-1.10.12-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2d5a58feb9a39f481eda4d5ca220aa8b9d4f21a41274760b9bc66bfd72595b86"}, + {file = "pydantic-1.10.12-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e5f805d2d5d0a41633651a73fa4ecdd0b3d7a49de4ec3fadf062fe16501ddbf1"}, + {file = "pydantic-1.10.12-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:1289c180abd4bd4555bb927c42ee42abc3aee02b0fb2d1223fb7c6e5bef87dbe"}, + {file = "pydantic-1.10.12-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5d1197e462e0364906cbc19681605cb7c036f2475c899b6f296104ad42b9f5fb"}, + {file = "pydantic-1.10.12-cp39-cp39-win_amd64.whl", hash = "sha256:fdbdd1d630195689f325c9ef1a12900524dceb503b00a987663ff4f58669b93d"}, + {file = "pydantic-1.10.12-py3-none-any.whl", hash = "sha256:b749a43aa51e32839c9d71dc67eb1e4221bb04af1033a32e3923d46f9effa942"}, + {file = "pydantic-1.10.12.tar.gz", hash = "sha256:0fe8a415cea8f340e7a9af9c54fc71a649b43e8ca3cc732986116b3cb135d303"}, +] + +[package.dependencies] +typing-extensions = ">=4.2.0" + +[package.extras] +dotenv = ["python-dotenv (>=0.10.4)"] +email = ["email-validator (>=1.0.3)"] + [[package]] name = "pygments" version = "2.16.1" @@ -906,23 +970,21 @@ use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] [[package]] name = "responses" -version = "0.23.3" +version = "0.10.15" description = "A utility library for mocking out the `requests` Python library." optional = false -python-versions = ">=3.7" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" files = [ - {file = "responses-0.23.3-py3-none-any.whl", hash = "sha256:e6fbcf5d82172fecc0aa1860fd91e58cbfd96cee5e96da5b63fa6eb3caa10dd3"}, - {file = "responses-0.23.3.tar.gz", hash = "sha256:205029e1cb334c21cb4ec64fc7599be48b859a0fd381a42443cdd600bfe8b16a"}, + {file = "responses-0.10.15-py2.py3-none-any.whl", hash = "sha256:af94d28cdfb48ded0ad82a5216616631543650f440334a693479b8991a6594a2"}, + {file = "responses-0.10.15.tar.gz", hash = "sha256:7bb697a5fedeb41d81e8b87f152d453d5cab42dcd1691b6a7d6097e94d33f373"}, ] [package.dependencies] -pyyaml = "*" -requests = ">=2.30.0,<3.0" -types-PyYAML = "*" -urllib3 = ">=1.25.10,<3.0" +requests = ">=2.0" +six = "*" [package.extras] -tests = ["coverage (>=6.0.0)", "flake8", "mypy", "pytest (>=7.0.0)", "pytest-asyncio", "pytest-cov", "pytest-httpserver", "tomli", "tomli-w", "types-requests"] +tests = ["coverage (>=3.7.1,<5.0.0)", "flake8", "pytest", "pytest (>=4.6,<5.0)", "pytest-cov", "pytest-localserver"] [[package]] name = "six" @@ -966,17 +1028,6 @@ notebook = ["ipywidgets (>=6)"] slack = ["slack-sdk"] telegram = ["requests"] -[[package]] -name = "types-pyyaml" -version = "6.0.12.12" -description = "Typing stubs for PyYAML" -optional = false -python-versions = "*" -files = [ - {file = "types-PyYAML-6.0.12.12.tar.gz", hash = "sha256:334373d392fde0fdf95af5c3f1661885fa10c52167b14593eb856289e1855062"}, - {file = "types_PyYAML-6.0.12.12-py3-none-any.whl", hash = "sha256:c05bc6c158facb0676674b7f11fe3960db4f389718e19e62bd2b84d6205cfd24"}, -] - [[package]] name = "typing-extensions" version = "4.8.0" @@ -1001,20 +1052,19 @@ files = [ [[package]] name = "urllib3" -version = "2.0.6" +version = "1.25.3" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false -python-versions = ">=3.7" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4" files = [ - {file = "urllib3-2.0.6-py3-none-any.whl", hash = "sha256:7a7c7003b000adf9e7ca2a377c9688bbc54ed41b985789ed576570342a375cd2"}, - {file = "urllib3-2.0.6.tar.gz", hash = "sha256:b19e1a85d206b56d7df1d5e683df4a7725252a964e3993648dd0fb5a1c157564"}, + {file = "urllib3-1.25.3-py2.py3-none-any.whl", hash = "sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1"}, + {file = "urllib3-1.25.3.tar.gz", hash = "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232"}, ] [package.extras] -brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] -secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"] -socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] -zstd = ["zstandard (>=0.18.0)"] +brotli = ["brotlipy (>=0.6.0)"] +secure = ["certifi", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "ipaddress", "pyOpenSSL (>=0.14)"] +socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] [[package]] name = "urllib3-mock" @@ -1064,4 +1114,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "81718e41eaf5215419a92230189a60fa2e061f93e550ddc692a65d19c5e75d7f" +content-hash = "59c7274e14abcf26e77715ecca2f5339ef46f61d1a267e3701e0031e607f5792" diff --git a/pyproject.toml b/pyproject.toml index e9b17b5d3..61c905ef9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,7 +61,7 @@ loguru = "0.5.3" typing-extensions = ">=3.7.4" dnspython = ">=2.0.0" python-dateutil = ">=2.5.3" -urllib3 = ">=1.21.1" +urllib3 = "1.25.3" tqdm = ">=4.64.1" numpy = ">=1.22.0" grpcio = ">=1.44.0" @@ -69,6 +69,8 @@ grpc-gateway-protoc-gen-openapiv2 = "0.1.0" googleapis-common-protos = ">=1.53.0" lz4 = ">=3.1.3" protobuf = "~=3.20.0" +aenum = "3.1.11" +pydantic = "1.10.12" [tool.poetry.group.dev.dependencies] pdoc = "^14.1.0" diff --git a/tests/integ/test_index.py b/tests/integ/test_index.py index 58fc3727c..cb52b6c56 100644 --- a/tests/integ/test_index.py +++ b/tests/integ/test_index.py @@ -8,128 +8,131 @@ from pinecone import ApiTypeError, ApiException responses_req = Responses() -responses = Responses('requests.packages.urllib3') +responses = Responses("requests.packages.urllib3") +@pytest.mark.skip() @req_responses.activate @responses.activate def test_invalid_upsert_request_vector_value_type(): - environment = 'example-environment' - project_name = 'example-project' + environment = "example-environment" + project_name = "example-project" req_responses.add( - 'GET', f'https://controller.{environment}.pinecone.io/actions/whoami', - status=200, content_type='application/json', - body=json.dumps(dict(project_name=project_name, user_label='example-label', user_name='test')) + "GET", + f"https://controller.{environment}.pinecone.io/actions/whoami", + status=200, + content_type="application/json", + body=json.dumps(dict(project_name=project_name, user_label="example-label", user_name="test")), ) responses.add( - 'POST', '/vectors/upsert', - status=400, content_type='text/plain', + "POST", + "/vectors/upsert", + status=400, + content_type="text/plain", adding_headers={ - 'content-length': '62', - 'date': 'Thu, 28 Oct 2021 09:14:51 GMT', - 'server': 'envoy', - 'connection': 'close' + "content-length": "62", + "date": "Thu, 28 Oct 2021 09:14:51 GMT", + "server": "envoy", + "connection": "close", }, - body='vectors[0].values[1]: invalid value "type" for type TYPE_FLOAT' + body='vectors[0].values[1]: invalid value "type" for type TYPE_FLOAT', ) - pinecone.init('example-api-key', environment='example-environment') + pinecone.init("example-api-key", environment="example-environment") with pytest.raises(ApiException) as exc_info: - index = pinecone.Index('example-index') - resp = index.upsert(vectors=[('vec1', [0.1]*8), ('vec2', [0.2]*8)]) + index = pinecone.Index("example-index") + resp = index.upsert(vectors=[("vec1", [0.1] * 8), ("vec2", [0.2] * 8)]) assert len(responses.calls) == 1 - assert responses.calls[0].request.scheme == 'https' - assert responses.calls[0].request.host == 'example-index-example-project.svc.example-environment.pinecone.io' - assert responses.calls[0].request.url == '/vectors/upsert' - + assert responses.calls[0].request.scheme == "https" + assert responses.calls[0].request.host == "example-index-example-project.svc.example-environment.pinecone.io" + assert responses.calls[0].request.url == "/vectors/upsert" +@pytest.mark.skip() @req_responses.activate @responses.activate def test_multiple_indexes(): - environment = 'example-environment' - project_name = 'example-project' - index1_name = 'index-1' - index2_name = 'index-2' + environment = "example-environment" + project_name = "example-project" + index1_name = "index-1" + index2_name = "index-2" req_responses.add( - 'GET', f'https://controller.{environment}.pinecone.io/actions/whoami', - status=200, content_type='application/json', - body=json.dumps(dict(project_name=project_name, user_label='example-label', user_name='test')) + "GET", + f"https://controller.{environment}.pinecone.io/actions/whoami", + status=200, + content_type="application/json", + body=json.dumps(dict(project_name=project_name, user_label="example-label", user_name="test")), ) responses.add( - 'GET', f'/describe_index_stats', - status=200, content_type='application/json', - adding_headers={ - 'date': 'Thu, 28 Oct 2021 09:14:51 GMT', - 'server': 'envoy' - }, - body='{"namespaces":{"":{"vectorCount":50000},"example-namespace-2":{"vectorCount":30000}},"dimension":1024}' + "GET", + f"/describe_index_stats", + status=200, + content_type="application/json", + adding_headers={"date": "Thu, 28 Oct 2021 09:14:51 GMT", "server": "envoy"}, + body='{"namespaces":{"":{"vectorCount":50000},"example-namespace-2":{"vectorCount":30000}},"dimension":1024}', ) - pinecone.init('example-api-key', environment='example-environment') + pinecone.init("example-api-key", environment="example-environment") index1 = pinecone.Index(index1_name) resp1 = index1.describe_index_stats() assert resp1.dimension == 1024 - assert responses.calls[0].request.host == f'{index1_name}-{project_name}.svc.{environment}.pinecone.io' + assert responses.calls[0].request.host == f"{index1_name}-{project_name}.svc.{environment}.pinecone.io" index2 = pinecone.Index(index2_name) resp2 = index2.describe_index_stats() assert resp2.dimension == 1024 - assert responses.calls[1].request.host == f'{index2_name}-{project_name}.svc.{environment}.pinecone.io' - + assert responses.calls[1].request.host == f"{index2_name}-{project_name}.svc.{environment}.pinecone.io" +@pytest.mark.skip() @req_responses.activate @responses.activate def test_invalid_delete_response_unrecognized_field(): # unrecognized response fields are okay, shouldn't raise an exception - environment = 'example-environment' - project_name = 'example-project' + environment = "example-environment" + project_name = "example-project" req_responses.add( - 'GET', f'https://controller.{environment}.pinecone.io/actions/whoami', - status=200, content_type='application/json', - body=json.dumps(dict(project_name=project_name, user_label='example-label', user_name='test')) + "GET", + f"https://controller.{environment}.pinecone.io/actions/whoami", + status=200, + content_type="application/json", + body=json.dumps(dict(project_name=project_name, user_label="example-label", user_name="test")), ) responses.add( - 'DELETE', '/vectors/delete', - body='{"unexpected_key": "xyzzy"}', - status=200, content_type='application/json' + "DELETE", "/vectors/delete", body='{"unexpected_key": "xyzzy"}', status=200, content_type="application/json" ) - pinecone.init('example-api-key', environment=environment) - index = pinecone.Index('example-index') - resp = index.delete(ids=['vec1', 'vec2']) + pinecone.init("example-api-key", environment=environment) + index = pinecone.Index("example-index") + resp = index.delete(ids=["vec1", "vec2"]) assert len(req_responses.calls) == 1 - assert responses.calls[0].request.scheme == 'https' - assert responses.calls[0].request.host == f'example-index-{project_name}.svc.{environment}.pinecone.io' - assert responses.calls[0].request.url == '/vectors/delete?ids=vec1&ids=vec2' - + assert responses.calls[0].request.scheme == "https" + assert responses.calls[0].request.host == f"example-index-{project_name}.svc.{environment}.pinecone.io" + assert responses.calls[0].request.url == "/vectors/delete?ids=vec1&ids=vec2" +@pytest.mark.skip() @responses.activate def test_delete_response_missing_field(): # missing (optional) response fields are okay, shouldn't raise an exception - pinecone.init('example-api-key', environment='example-environment') - responses.add('DELETE', '/vectors/delete', - body='{}', - status=200, content_type='application/json') - index = pinecone.Index('example-index') + pinecone.init("example-api-key", environment="example-environment") + responses.add("DELETE", "/vectors/delete", body="{}", status=200, content_type="application/json") + index = pinecone.Index("example-index") # this should not raise - index.delete(ids=['vec1', 'vec2']) - - + index.delete(ids=["vec1", "vec2"]) +@pytest.mark.skip() @responses.activate def _test_invalid_delete_response_wrong_type(): # FIXME: re-enable this test when accepted_count added back to response # wrong-typed response fields should raise an exception - pinecone.init('example-api-key', environment='example-environment') + pinecone.init("example-api-key", environment="example-environment") - responses.add('DELETE', '/vectors/delete', - body='{"deleted_count": "foobar"}', - status=200, content_type='application/json') + responses.add( + "DELETE", "/vectors/delete", body='{"deleted_count": "foobar"}', status=200, content_type="application/json" + ) - index = pinecone.Index('example-index') + index = pinecone.Index("example-index") with pytest.raises(ApiTypeError) as exc_info: - resp = index.delete(ids=['vec1', 'vec2']) + resp = index.delete(ids=["vec1", "vec2"]) assert resp.deleted_count == 2 diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 5251b67c2..7fec4826b 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -6,210 +6,204 @@ import tempfile import os + @pytest.fixture(autouse=True) def run_before_and_after_tests(tmpdir): """Fixture to execute asserts before and after a test is run""" - + # Defend against unexpected env vars. Since we clear these variables below - # after each test execution, these should only be raised if there is + # after each test execution, these should only be raised if there is # test pollution in the environment coming from some other test file/setup. - known_env_vars = ['PINECONE_API_KEY', 'PINECONE_ENVIRONMENT', 'PINECONE_PROJECT_NAME', 'PINECONE_CONTROLLER_HOST'] + known_env_vars = ["PINECONE_API_KEY", "PINECONE_ENVIRONMENT", "PINECONE_CONTROLLER_HOST"] for var in known_env_vars: if os.getenv(var): - raise ValueError(f'Unexpected env var {var} found in environment. Check for test pollution.') + raise ValueError(f"Unexpected env var {var} found in environment. Check for test pollution.") # Unfortunately since config is a singleton, we need to reset it manually between tests pinecone.init() - yield # this is where the testing happens + yield # this is where the testing happens # Teardown : Unset any env vars created during test execution for var in known_env_vars: if os.getenv(var): del os.environ[var] + def test_default_config(): """ Test that default config is loaded when no config is specified. This not really a valid config that can be used, but adding this test just to document the legacy behavior. """ pinecone.init() - assert Config.API_KEY == '' - assert Config.ENVIRONMENT == 'us-west1-gcp' - assert Config.PROJECT_NAME == 'UNKNOWN' - assert Config.CONTROLLER_HOST == 'https://controller.us-west1-gcp.pinecone.io' - assert Config.LOG_LEVEL == 'ERROR' + assert Config.API_KEY == "" + assert Config.ENVIRONMENT == "us-west1-gcp" + assert Config.CONTROLLER_HOST == "https://controller.us-west1-gcp.pinecone.io" + assert Config.LOG_LEVEL == "ERROR" + def test_init_with_environment_vars(): - os.environ['PINECONE_ENVIRONMENT'] = 'test-env' - os.environ['PINECONE_API_KEY'] = 'test-api-key' - os.environ['PINECONE_PROJECT_NAME'] = 'test-project-name' - os.environ['PINECONE_CONTROLLER_HOST'] = 'test-controller-host' + os.environ["PINECONE_ENVIRONMENT"] = "test-env" + os.environ["PINECONE_API_KEY"] = "test-api-key" + os.environ["PINECONE_CONTROLLER_HOST"] = "test-controller-host" pinecone.init() - assert Config.API_KEY == 'test-api-key' - assert Config.ENVIRONMENT == 'test-env' - assert Config.PROJECT_NAME == 'test-project-name' - assert Config.CONTROLLER_HOST == 'test-controller-host' + assert Config.API_KEY == "test-api-key" + assert Config.ENVIRONMENT == "test-env" + assert Config.CONTROLLER_HOST == "test-controller-host" + def test_init_with_positional_args(): - api_key = 'my-api-key' - environment = 'test-env' - host = 'my-controller-host' - project_name = 'my-project-name' - log_level = None # deprecated property but still in positional list - openapi_config = OpenApiConfiguration(api_key='openapi-api-key') + api_key = "my-api-key" + environment = "test-env" + host = "my-controller-host" + log_level = None # deprecated property but still in positional list + openapi_config = OpenApiConfiguration(api_key="openapi-api-key") - pinecone.init(api_key, host, environment, project_name, log_level, openapi_config) + pinecone.init(api_key, host, environment, log_level, openapi_config) assert Config.API_KEY == api_key assert Config.ENVIRONMENT == environment - assert Config.PROJECT_NAME == project_name assert Config.CONTROLLER_HOST == host assert Config.OPENAPI_CONFIG == openapi_config + def test_init_with_kwargs(): - env = 'test-env' - api_key = 'my-api-key' - project_name = 'my-project-name' - controller_host = 'my-controller-host' - openapi_config = OpenApiConfiguration(api_key='openapi-api-key') + env = "test-env" + api_key = "my-api-key" + controller_host = "my-controller-host" + openapi_config = OpenApiConfiguration(api_key="openapi-api-key") - pinecone.init(api_key=api_key, environment=env, project_name=project_name, host=controller_host, openapi_config=openapi_config) + pinecone.init(api_key=api_key, environment=env, host=controller_host, openapi_config=openapi_config) assert Config.API_KEY == api_key assert Config.ENVIRONMENT == env - assert Config.PROJECT_NAME == project_name assert Config.CONTROLLER_HOST == controller_host assert Config.OPENAPI_CONFIG == openapi_config + def test_init_with_mispelled_kwargs(caplog): pinecone.init(invalid_kwarg="value") - assert 'init had unexpected keyword argument(s): invalid_kwarg' in caplog.text + assert "init had unexpected keyword argument(s): invalid_kwarg" in caplog.text + def test_init_with_file_based_configuration(): """Test that config can be loaded from a file""" - env = 'ini-test-env' - api_key = 'ini-api-key' - project_name = 'ini-project-name' - controller_host = 'ini-controller-host' + env = "ini-test-env" + api_key = "ini-api-key" + controller_host = "ini-controller-host" - with tempfile.NamedTemporaryFile(mode='w') as f: - f.write(f""" + with tempfile.NamedTemporaryFile(mode="w") as f: + f.write( + f""" [default] environment: {env} api_key: {api_key} - project_name: {project_name} controller_host: {controller_host} - """) + """ + ) f.flush() pinecone.init(config=f.name) assert Config.API_KEY == api_key assert Config.ENVIRONMENT == env - assert Config.PROJECT_NAME == project_name assert Config.CONTROLLER_HOST == controller_host + def test_resolution_order_kwargs_over_env_vars(): """ - Test that when config is present from multiple sources, + Test that when config is present from multiple sources, the order of precedence is kwargs > env vars """ - os.environ['PINECONE_ENVIRONMENT'] = 'env-var-env' - os.environ['PINECONE_API_KEY'] = 'env-var-api-key' - os.environ['PINECONE_PROJECT_NAME'] = 'env-var-project-name' - os.environ['PINECONE_CONTROLLER_HOST'] = 'env-var-controller-host' + os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" + os.environ["PINECONE_API_KEY"] = "env-var-api-key" + os.environ["PINECONE_CONTROLLER_HOST"] = "env-var-controller-host" - env = 'kwargs-env' - api_key = 'kwargs-api-key' - project_name = 'kwargs-project-name' - controller_host = 'kwargs-controller-host' + env = "kwargs-env" + api_key = "kwargs-api-key" + controller_host = "kwargs-controller-host" - pinecone.init(environment=env, api_key=api_key, project_name=project_name, host=controller_host) + pinecone.init(environment=env, api_key=api_key, host=controller_host) assert Config.API_KEY == api_key assert Config.ENVIRONMENT == env - assert Config.PROJECT_NAME == project_name assert Config.CONTROLLER_HOST == controller_host + def test_resolution_order_kwargs_over_config_file(): """ - Test that when config is present from multiple sources, the order of + Test that when config is present from multiple sources, the order of precedence is kwargs > config file """ - env = 'ini-test-env' - api_key = 'ini-api-key' - project_name = 'ini-project-name' - controller_host = 'ini-controller-host' + env = "ini-test-env" + api_key = "ini-api-key" + controller_host = "ini-controller-host" - kwargs_api_key = 'kwargs-api-key' - kwargs_project_name = 'kwargs-project-name' + kwargs_api_key = "kwargs-api-key" - with tempfile.NamedTemporaryFile(mode='w') as f: - f.write(f""" + with tempfile.NamedTemporaryFile(mode="w") as f: + f.write( + f""" [default] environment: {env} api_key: {api_key} - project_name: {project_name} controller_host: {controller_host} - """) + """ + ) f.flush() - pinecone.init(api_key=kwargs_api_key, project_name=kwargs_project_name, config=f.name) + pinecone.init(api_key=kwargs_api_key, config=f.name) # Properties passed as kwargs take precedence over config file assert Config.API_KEY == kwargs_api_key - assert Config.PROJECT_NAME == kwargs_project_name # Properties not passed as kwargs loaded from config file assert Config.ENVIRONMENT == env assert Config.CONTROLLER_HOST == controller_host + def test_resolution_order_env_vars_over_config_file(): """ - Test that when config is present from multiple sources, the order of precedence is + Test that when config is present from multiple sources, the order of precedence is env vars > config file """ - - os.environ['PINECONE_ENVIRONMENT'] = 'env-var-env' - os.environ['PINECONE_API_KEY'] = 'env-var-api-key' - os.environ['PINECONE_PROJECT_NAME'] = 'env-var-project-name' - os.environ['PINECONE_CONTROLLER_HOST'] = 'env-var-controller-host' - - with tempfile.NamedTemporaryFile(mode='w') as f: - f.write(f""" + + os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" + os.environ["PINECONE_API_KEY"] = "env-var-api-key" + os.environ["PINECONE_CONTROLLER_HOST"] = "env-var-controller-host" + + with tempfile.NamedTemporaryFile(mode="w") as f: + f.write( + f""" [default] environment: ini-test-env api_key: ini-api-key - project_name: ini-project-name controller_host: ini-controller-host - """) + """ + ) f.flush() pinecone.init(config=f.name) - assert Config.API_KEY == 'env-var-api-key' - assert Config.ENVIRONMENT == 'env-var-env' - assert Config.PROJECT_NAME == 'env-var-project-name' - assert Config.CONTROLLER_HOST == 'env-var-controller-host' - + assert Config.API_KEY == "env-var-api-key" + assert Config.ENVIRONMENT == "env-var-env" + assert Config.CONTROLLER_HOST == "env-var-controller-host" + def test_init_from_mixed_sources(): """ - Test that even when some vars are found in a higher precedence source, the rest + Test that even when some vars are found in a higher precedence source, the rest are still loaded from lower precedence sources """ - os.environ['PINECONE_ENVIRONMENT'] = 'env-var-env' - os.environ['PINECONE_API_KEY'] = 'env-var-api-key' - project_name = 'kwargs-project-name' - controller_host = 'kwargs-controller-host' + os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" + os.environ["PINECONE_API_KEY"] = "env-var-api-key" + controller_host = "kwargs-controller-host" - pinecone.init(project_name=project_name, host=controller_host) + pinecone.init(host=controller_host) - assert Config.API_KEY == 'env-var-api-key' - assert Config.ENVIRONMENT == 'env-var-env' - assert Config.PROJECT_NAME == project_name - assert Config.CONTROLLER_HOST == controller_host \ No newline at end of file + assert Config.API_KEY == "env-var-api-key" + assert Config.ENVIRONMENT == "env-var-env" + assert Config.CONTROLLER_HOST == controller_host diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 2284d81ff..036ac126a 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -6,13 +6,22 @@ import pinecone from pinecone import DescribeIndexStatsRequest -from pinecone.core.grpc.protos.vector_service_pb2 import Vector, DescribeIndexStatsRequest, UpdateRequest, \ - UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector, UpsertResponse, SparseValues -from pinecone.core.utils import dict_to_proto_struct +from pinecone.core.grpc.protos.vector_service_pb2 import ( + Vector, + DescribeIndexStatsRequest, + UpdateRequest, + UpsertRequest, + FetchRequest, + QueryRequest, + DeleteRequest, + QueryVector, + UpsertResponse, + SparseValues, +) +from pinecone.utils import dict_to_proto_struct class TestGrpcIndex: - def setup_method(self): self.vector_dim = 8 self.vals1 = [0.1] * self.vector_dim @@ -21,128 +30,162 @@ def setup_method(self): self.sparse_values_1 = [0.8, 0.9, 0.42] self.sparse_indices_2 = [1, 3, 5] self.sparse_values_2 = [0.7, 0.3, 0.31415] - self.md1 = {'genre': 'action', 'year': 2021} - self.md2 = {'genre': 'documentary', 'year': 2020} - self.filter1 = {'genre': {'$in': ['action']}} - self.filter2 = {'year': {'$eq': 2020}} - - pinecone.init(api_key='example-key') - self.index = pinecone.GRPCIndex('example-name') - - self.expected_vec1 = Vector(id='vec1', values=self.vals1, metadata={}) - self.expected_vec2 = Vector(id='vec2', values=self.vals2, metadata={}) - self.expected_vec_md1 = Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)) - self.expected_vec_md2 = Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2)) - self.expected_vec_md_sparse1 = Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1)) - self.expected_vec_md_sparse2 = Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2)) - + self.md1 = {"genre": "action", "year": 2021} + self.md2 = {"genre": "documentary", "year": 2020} + self.filter1 = {"genre": {"$in": ["action"]}} + self.filter2 = {"year": {"$eq": 2020}} + + pinecone.init(api_key="example-key") + self.index = pinecone.GRPCIndex("example-name") + + self.expected_vec1 = Vector(id="vec1", values=self.vals1, metadata={}) + self.expected_vec2 = Vector(id="vec2", values=self.vals2, metadata={}) + self.expected_vec_md1 = Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1)) + self.expected_vec_md2 = Vector(id="vec2", values=self.vals2, metadata=dict_to_proto_struct(self.md2)) + self.expected_vec_md_sparse1 = Vector( + id="vec1", + values=self.vals1, + metadata=dict_to_proto_struct(self.md1), + sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), + ) + self.expected_vec_md_sparse2 = Vector( + id="vec2", + values=self.vals2, + metadata=dict_to_proto_struct(self.md2), + sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), + ) # region: upsert tests def _assert_called_once(self, vectors, async_call=False): self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Upsert.future if async_call else self.index.stub.Upsert, - UpsertRequest( - vectors=vectors, - namespace='ns'), - timeout=None + UpsertRequest(vectors=vectors, namespace="ns"), + timeout=None, ) def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') - self._assert_called_once([ - self.expected_vec1, - self.expected_vec2 - ]) - + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([("vec1", self.vals1), ("vec2", self.vals2)], namespace="ns") + self._assert_called_once([self.expected_vec1, self.expected_vec2]) def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.upsert([('vec1', self.vals1, self.md1), ('vec2', self.vals2, self.md2)], namespace='ns') - self._assert_called_once([ - self.expected_vec_md1, - self.expected_vec_md2], + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2)], namespace="ns") + self._assert_called_once( + [self.expected_vec_md1, self.expected_vec_md2], ) def test_upsert_vectors_upsertInputVectors(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.upsert([self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns') - self._assert_called_once([ - self.expected_vec_md1, - self.expected_vec_md2], + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns") + self._assert_called_once( + [self.expected_vec_md1, self.expected_vec_md2], ) - def test_upsert_vectors_upsertInputVectorsSparse(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1)), - Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2))], - namespace='ns') + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert( + [ + Vector( + id="vec1", + values=self.vals1, + metadata=dict_to_proto_struct(self.md1), + sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), + ), + Vector( + id="vec2", + values=self.vals2, + metadata=dict_to_proto_struct(self.md2), + sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), + ), + ], + namespace="ns", + ) self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2]) def test_upsert_dict(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - dict1 = {'id': 'vec1', 'values': self.vals1} - dict2 = {'id': 'vec2', 'values': self.vals2} - self.index.upsert([dict1, dict2], namespace='ns') - self._assert_called_once([ - self.expected_vec1, - self.expected_vec2] - ) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = {"id": "vec1", "values": self.vals1} + dict2 = {"id": "vec2", "values": self.vals2} + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once([self.expected_vec1, self.expected_vec2]) def test_upsert_dict_md(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - dict1 = {'id': 'vec1', 'values': self.vals1, 'metadata': self.md1} - dict2 = {'id': 'vec2', 'values': self.vals2, 'metadata': self.md2} - self.index.upsert([dict1, dict2], namespace='ns') - self._assert_called_once([ - self.expected_vec_md1, - self.expected_vec_md2] - ) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = {"id": "vec1", "values": self.vals1, "metadata": self.md1} + dict2 = {"id": "vec2", "values": self.vals2, "metadata": self.md2} + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once([self.expected_vec_md1, self.expected_vec_md2]) def test_upsert_dict_sparse(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}} - dict2 = {'id': 'vec2', 'values': self.vals2, - 'sparse_values': {'indices': self.sparse_indices_2, 'values': self.sparse_values_2}} - self.index.upsert([dict1, dict2], namespace='ns') - self._assert_called_once([ - Vector(id='vec1', values=self.vals1, metadata={}, - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1)), - Vector(id='vec2', values=self.vals2, metadata={}, - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2))] + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + } + dict2 = { + "id": "vec2", + "values": self.vals2, + "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, + } + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once( + [ + Vector( + id="vec1", + values=self.vals1, + metadata={}, + sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), + ), + Vector( + id="vec2", + values=self.vals2, + metadata={}, + sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), + ), + ] ) def test_upsert_dict_sparse_md(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1} - dict2 = {'id': 'vec2', 'values': self.vals2, - 'sparse_values': {'indices': self.sparse_indices_2, 'values': self.sparse_values_2}, - 'metadata': self.md2} - self.index.upsert([dict1, dict2], namespace='ns') - self._assert_called_once([ - Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1)), - Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2))] + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + } + dict2 = { + "id": "vec2", + "values": self.vals2, + "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, + "metadata": self.md2, + } + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once( + [ + Vector( + id="vec1", + values=self.vals1, + metadata=dict_to_proto_struct(self.md1), + sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), + ), + Vector( + id="vec2", + values=self.vals2, + metadata=dict_to_proto_struct(self.md2), + sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), + ), + ] ) def test_upsert_dict_negative(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) # Missing required keys - dict1 = {'values': self.vals1} - dict2 = {'id': 'vec2'} + dict1 = {"values": self.vals1} + dict2 = {"id": "vec2"} with pytest.raises(ValueError): self.index.upsert([dict1, dict2]) with pytest.raises(ValueError): @@ -151,50 +194,62 @@ def test_upsert_dict_negative(self, mocker): self.index.upsert([dict2]) # Excess keys - dict1 = {'id': 'vec1', 'values': self.vals1} - dict2 = {'id': 'vec2', 'values': self.vals2, 'animal': 'dog'} + dict1 = {"id": "vec1", "values": self.vals1} + dict2 = {"id": "vec2", "values": self.vals2, "animal": "dog"} with pytest.raises(ValueError) as e: self.index.upsert([dict1, dict2]) - assert 'animal' in str(e.value) + assert "animal" in str(e.value) - dict1 = {'id': 'vec1', 'values': self.vals1, 'metadatta': self.md2} - dict2 = {'id': 'vec2', 'values': self.vals2} + dict1 = {"id": "vec1", "values": self.vals1, "metadatta": self.md2} + dict2 = {"id": "vec2", "values": self.vals2} with pytest.raises(ValueError) as e: self.index.upsert([dict1, dict2]) - assert 'metadatta' in str(e.value) - - @pytest.mark.parametrize("key,new_val", [ - ("values", ['the', 'lazy', 'fox']), - ("values", 'the lazy fox'), - ("values", 0.5), - ("metadata", np.nan), - ("metadata", ['key1', 'key2']), - ("sparse_values", 'cat'), - ("sparse_values", []), - ]) + assert "metadatta" in str(e.value) + + @pytest.mark.parametrize( + "key,new_val", + [ + ("values", ["the", "lazy", "fox"]), + ("values", "the lazy fox"), + ("values", 0.5), + ("metadata", np.nan), + ("metadata", ["key1", "key2"]), + ("sparse_values", "cat"), + ("sparse_values", []), + ], + ) def test_upsert_dict_with_invalid_values(self, mocker, key, new_val): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - full_dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1} + full_dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + } dict1 = deepcopy(full_dict1) dict1[key] = new_val with pytest.raises(TypeError) as e: self.index.upsert([dict1]) assert key in str(e.value) - - @pytest.mark.parametrize("key,new_val", [ - ("id", 4.2), - ("id", ['vec1']), - ]) + + @pytest.mark.parametrize( + "key,new_val", + [ + ("id", 4.2), + ("id", ["vec1"]), + ], + ) def test_upsert_dict_with_invalid_ids(self, mocker, key, new_val): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - full_dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1} + full_dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + } dict1 = deepcopy(full_dict1) dict1[key] = new_val @@ -202,66 +257,96 @@ def test_upsert_dict_with_invalid_ids(self, mocker, key, new_val): self.index.upsert([dict1]) assert str(new_val) in str(e.value) - @pytest.mark.parametrize("key,new_val", [ - ("indices", 3), - ("indices", [1.2, 0.5]), - ("values", ['1', '4.4']), - ("values", 0.5), - ]) + @pytest.mark.parametrize( + "key,new_val", + [ + ("indices", 3), + ("indices", [1.2, 0.5]), + ("values", ["1", "4.4"]), + ("values", 0.5), + ], + ) def test_upsert_dict_with_invalid_sparse_values(self, mocker, key, new_val): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - full_dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1} + full_dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + } dict1 = deepcopy(full_dict1) - dict1['sparse_values'][key] = new_val + dict1["sparse_values"][key] = new_val with pytest.raises(TypeError) as e: self.index.upsert([dict1]) - assert 'sparse' in str(e.value) + assert "sparse" in str(e.value) assert key in str(e.value) def test_upsert_dataframe(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: MockUpsertDelegate(UpsertResponse( - upserted_count=len(upsert_request.vectors)))) - df = pd.DataFrame([ - {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1}, - {'id': 'vec2', 'values': self.vals2, - 'sparse_values': {'indices': self.sparse_indices_2, 'values': self.sparse_values_2}, - 'metadata': self.md2} - ]) - self.index.upsert_from_dataframe(df, namespace='ns') - self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], - async_call=True + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: MockUpsertDelegate( + UpsertResponse(upserted_count=len(upsert_request.vectors)) + ), ) - + df = pd.DataFrame( + [ + { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + }, + { + "id": "vec2", + "values": self.vals2, + "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, + "metadata": self.md2, + }, + ] + ) + self.index.upsert_from_dataframe(df, namespace="ns") + self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], async_call=True) def test_upsert_dataframe_sync(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - df = pd.DataFrame([ - {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1}, - {'id': 'vec2', 'values': self.vals2, - 'sparse_values': {'indices': self.sparse_indices_2, 'values': self.sparse_values_2}, - 'metadata': self.md2} - ]) - self.index.upsert_from_dataframe(df, namespace='ns', use_async_requests=False) - self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], - async_call=False + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + df = pd.DataFrame( + [ + { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + }, + { + "id": "vec2", + "values": self.vals2, + "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, + "metadata": self.md2, + }, + ] ) + self.index.upsert_from_dataframe(df, namespace="ns", use_async_requests=False) + self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], async_call=False) def test_upsert_dataframe_negative(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - full_dict1 = {'id': 'vec1', 'values': self.vals1, - 'sparse_values': {'indices': self.sparse_indices_1, 'values': self.sparse_values_1}, - 'metadata': self.md1} + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + full_dict1 = { + "id": "vec1", + "values": self.vals1, + "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, + "metadata": self.md1, + } full_df = pd.DataFrame([full_dict1]) # Not a DF @@ -272,156 +357,166 @@ def test_upsert_dataframe_negative(self, mocker): # Missing Cols df = full_df.copy() - df.drop(columns=['id'], inplace=True) + df.drop(columns=["id"], inplace=True) with pytest.raises(ValueError): self.index.upsert_from_dataframe(df) # Excess cols df = full_df.copy() - df['animals'] = ['dog'] + df["animals"] = ["dog"] with pytest.raises(ValueError): self.index.upsert_from_dataframe(df) df = full_df.copy() - df['metadat'] = df['metadata'] + df["metadat"] = df["metadata"] with pytest.raises(ValueError): self.index.upsert_from_dataframe(df) def test_upsert_async_upsertInputVectorsAsync(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.upsert([self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns', - async_req=True) - self._assert_called_once([ - self.expected_vec_md1, - self.expected_vec_md2], - async_call=True - ) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns", async_req=True) + self._assert_called_once([self.expected_vec_md1, self.expected_vec_md2], async_call=True) def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert([self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns', - batch_size=1, - show_progress=False) + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [self.expected_vec_md1, self.expected_vec_md2], namespace="ns", batch_size=1, show_progress=False + ) self.index._wrap_grpc_call.assert_any_call( self.index.stub.Upsert, UpsertRequest( - vectors=[ - Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns'), - timeout=None) + vectors=[Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" + ), + timeout=None, + ) self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest( - vectors=[self.expected_vec_md2], - namespace='ns'), - timeout=None) + self.index.stub.Upsert, UpsertRequest(vectors=[self.expected_vec_md2], namespace="ns"), timeout=None + ) assert result.upserted_count == 2 def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert([self.expected_vec_md1, - Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2)), - Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns', - batch_size=2) + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [ + self.expected_vec_md1, + Vector(id="vec2", values=self.vals2, metadata=dict_to_proto_struct(self.md2)), + Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + ], + namespace="ns", + batch_size=2, + ) self.index._wrap_grpc_call.assert_any_call( self.index.stub.Upsert, - UpsertRequest( - vectors=[ - self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns'), - timeout=None) + UpsertRequest(vectors=[self.expected_vec_md1, self.expected_vec_md2], namespace="ns"), + timeout=None, + ) self.index._wrap_grpc_call.assert_any_call( self.index.stub.Upsert, UpsertRequest( - vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns'), - timeout=None) + vectors=[Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" + ), + timeout=None, + ) assert result.upserted_count == 3 def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors))) + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) - result = self.index.upsert([self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns', - batch_size=5) - self._assert_called_once([ - self.expected_vec_md1, - self.expected_vec_md2], + result = self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns", batch_size=5) + self._assert_called_once( + [self.expected_vec_md1, self.expected_vec_md2], ) assert result.upserted_count == 2 def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert([('vec1', self.vals1, self.md1), - ('vec2', self.vals2, self.md2), - ('vec3', self.vals1, self.md1)], - namespace='ns', - batch_size=2) + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2), ("vec3", self.vals1, self.md1)], + namespace="ns", + batch_size=2, + ) self.index._wrap_grpc_call.assert_any_call( self.index.stub.Upsert, - UpsertRequest( - vectors=[ - self.expected_vec_md1, - self.expected_vec_md2], - namespace='ns'), - timeout=None) + UpsertRequest(vectors=[self.expected_vec_md1, self.expected_vec_md2], namespace="ns"), + timeout=None, + ) self.index._wrap_grpc_call.assert_any_call( self.index.stub.Upsert, UpsertRequest( - vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns'), - timeout=None) + vectors=[Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" + ), + timeout=None, + ) assert result.upserted_count == 3 def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): - with pytest.raises(ValueError, match='batch_size must be a positive integer'): - self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns', - batch_size=0) - - with pytest.raises(ValueError, match='batch_size must be a positive integer'): - self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns', - batch_size=-1) + with pytest.raises(ValueError, match="batch_size must be a positive integer"): + self.index.upsert( + [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace="ns", + batch_size=0, + ) + + with pytest.raises(ValueError, match="batch_size must be a positive integer"): + self.index.upsert( + [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace="ns", + batch_size=-1, + ) def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): - with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): - self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace='ns', - batch_size=2, - async_req=True) + with pytest.raises(ValueError, match="async_req is not supported when batch_size is provided."): + self.index.upsert( + [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace="ns", + batch_size=2, + async_req=True, + ) # endregion # region: query tests def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) self.index.query(top_k=10, vector=self.vals1) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Query, @@ -430,50 +525,46 @@ def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): ) def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns', timeout=10) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns", timeout=10) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Query, - QueryRequest(top_k=10, vector=self.vals1, filter=dict_to_proto_struct(self.filter1), namespace='ns'), + QueryRequest(top_k=10, vector=self.vals1, filter=dict_to_proto_struct(self.filter1), namespace="ns"), timeout=10, ) def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.query(top_k=10, queries=[ - (self.vals1,), - (self.vals2,) - ]) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, queries=[(self.vals1,), (self.vals2,)]) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Query, - QueryRequest(queries=[ - QueryVector(values=self.vals1, filter={}), - QueryVector(values=self.vals2, filter={}) - ], top_k=10), + QueryRequest( + queries=[QueryVector(values=self.vals1, filter={}), QueryVector(values=self.vals2, filter={})], top_k=10 + ), timeout=None, ) def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.query(top_k=10, queries=[ - (self.vals1, self.filter1), - (self.vals2, self.filter2) - ]) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, queries=[(self.vals1, self.filter1), (self.vals2, self.filter2)]) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Query, - QueryRequest(queries=[ - QueryVector(values=self.vals1, filter=dict_to_proto_struct(self.filter1)), - QueryVector(values=self.vals2, filter=dict_to_proto_struct(self.filter2)) - ], top_k=10), + QueryRequest( + queries=[ + QueryVector(values=self.vals1, filter=dict_to_proto_struct(self.filter1)), + QueryVector(values=self.vals2, filter=dict_to_proto_struct(self.filter2)), + ], + top_k=10, + ), timeout=None, ) def test_query_byVecId_queryByVecId(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.query(top_k=10, id='vec1', include_metadata=True, include_values=False) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Query, - QueryRequest(top_k=10, id='vec1', include_metadata=True, include_values=False), + QueryRequest(top_k=10, id="vec1", include_metadata=True, include_values=False), timeout=None, ) @@ -482,34 +573,34 @@ def test_query_byVecId_queryByVecId(self, mocker): # region: delete tests def test_delete_byIds_deleteByIds(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.delete(ids=['vec1', 'vec2']) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.delete(ids=["vec1", "vec2"]) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Delete, - DeleteRequest(ids=['vec1', 'vec2']), + DeleteRequest(ids=["vec1", "vec2"]), timeout=None, ) def test_delete_byIdsAsync_deleteByIdsAsync(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.delete(ids=['vec1', 'vec2'], async_req=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.delete(ids=["vec1", "vec2"], async_req=True) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Delete.future, - DeleteRequest(ids=['vec1', 'vec2']), + DeleteRequest(ids=["vec1", "vec2"]), timeout=None, ) def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.delete(delete_all=True, filter=self.filter1, namespace='ns', timeout=30) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.delete(delete_all=True, filter=self.filter1, namespace="ns", timeout=30) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Delete, - DeleteRequest(delete_all=True, filter=dict_to_proto_struct(self.filter1), namespace='ns'), + DeleteRequest(delete_all=True, filter=dict_to_proto_struct(self.filter1), namespace="ns"), timeout=30, ) def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) self.index.delete(delete_all=True) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Delete, @@ -522,20 +613,20 @@ def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): # region: fetch tests def test_fetch_byIds_fetchByIds(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.fetch(['vec1', 'vec2']) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.fetch(["vec1", "vec2"]) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Fetch, - FetchRequest(ids=['vec1', 'vec2']), + FetchRequest(ids=["vec1", "vec2"]), timeout=None, ) def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.fetch(['vec1', 'vec2'], namespace='ns', timeout=30) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.fetch(["vec1", "vec2"], namespace="ns", timeout=30) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Fetch, - FetchRequest(ids=['vec1', 'vec2'], namespace='ns'), + FetchRequest(ids=["vec1", "vec2"], namespace="ns"), timeout=30, ) @@ -544,29 +635,29 @@ def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): # region: update tests def test_update_byIdAnValues_updateByIdAndValues(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.update(id='vec1', values=self.vals1, namespace='ns', timeout=30) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update(id="vec1", values=self.vals1, namespace="ns", timeout=30) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Update, - UpdateRequest(id='vec1', values=self.vals1, namespace='ns'), + UpdateRequest(id="vec1", values=self.vals1, namespace="ns"), timeout=30, ) def test_update_byIdAnValuesAsync_updateByIdAndValuesAsync(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.update(id='vec1', values=self.vals1, namespace='ns', timeout=30, async_req=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update(id="vec1", values=self.vals1, namespace="ns", timeout=30, async_req=True) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Update.future, - UpdateRequest(id='vec1', values=self.vals1, namespace='ns'), + UpdateRequest(id="vec1", values=self.vals1, namespace="ns"), timeout=30, ) def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) - self.index.update('vec1', values=self.vals1, set_metadata=self.md1) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update("vec1", values=self.vals1, set_metadata=self.md1) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.Update, - UpdateRequest(id='vec1', values=self.vals1, set_metadata=dict_to_proto_struct(self.md1)), + UpdateRequest(id="vec1", values=self.vals1, set_metadata=dict_to_proto_struct(self.md1)), timeout=None, ) @@ -575,7 +666,7 @@ def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, moc # region: describe index tests def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) self.index.describe_index_stats() self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.DescribeIndexStats, @@ -584,7 +675,7 @@ def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): ) def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): - mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) self.index.describe_index_stats(filter=self.filter1) self.index._wrap_grpc_call.assert_called_once_with( self.index.stub.DescribeIndexStats, @@ -594,9 +685,10 @@ def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): # endregion + class MockUpsertDelegate: def __init__(self, upsert_response: UpsertResponse): self.response = upsert_response def result(self, timeout): - return self.response \ No newline at end of file + return self.response diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 7092d71cf..28d502b39 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -3,36 +3,31 @@ import pytest import warnings -from pinecone.core.client.api_client import Endpoint - import pinecone +from pinecone import UpsertRequest, Vector from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse, UpsertResponse, SparseValues class TestRestIndex: - def setup_method(self): self.vector_dim = 8 - self.id1 = 'vec1' - self.id2 = 'vec2' + self.id1 = "vec1" + self.id2 = "vec2" self.vals1 = [0.1] * self.vector_dim self.vals2 = [0.2] * self.vector_dim - self.md1 = {'genre': 'action', 'year': 2021} - self.md2 = {'genre': 'documentary', 'year': 2020} - self.filter1 = {'genre': {'$in': ['action']}} - self.filter2 = {'year': {'$eq': 2020}} + self.md1 = {"genre": "action", "year": 2021} + self.md2 = {"genre": "documentary", "year": 2020} + self.filter1 = {"genre": {"$in": ["action"]}} + self.filter2 = {"year": {"$eq": 2020}} self.svi1 = [1, 3, 5] self.svv1 = [0.1, 0.2, 0.3] self.sv1 = { - 'indices': self.svi1, - 'values': self.svv1, + "indices": self.svi1, + "values": self.svv1, } self.svi2 = [2, 4, 6] self.svv2 = [0.1, 0.2, 0.3] - self.sv2 = { - 'indices': self.svi2, - 'values': self.svv2 - } + self.sv2 = {"indices": self.svi2, "values": self.svv2} pinecone.init(api_key='example-key') self.index = pinecone.Index('example-name') @@ -49,314 +44,364 @@ def test_upsert_numpy_deprecation_warning(self, mocker): self.index.upsert([{'id': '3', 'values': [0.5,0.5,0.5], 'sparse_values': { 'indices': np.array([0, 1]), 'values': np.array([3.0, 3.2])}}]) def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert([("vec1", self.vals1), ("vec2", self.vals2)], namespace="ns") self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata={}), - pinecone.Vector(id='vec2', values=self.vals2, metadata={}) - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata={}), + Vector(id="vec2", values=self.vals2, metadata={}), + ], + namespace="ns", + ) ) def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert([('vec1', self.vals1, self.md1), - ('vec2', self.vals2, self.md2)]) + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert([("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2)]) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) - ]) + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ] + ) ) def test_upsert_dictOfIdVecMD_UpsertVectorsWithMD(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert([{'id': self.id1, 'values': self.vals1, 'metadata': self.md1}, - {'id': self.id2, 'values': self.vals2, 'metadata': self.md2}]) + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert( + [ + {"id": self.id1, "values": self.vals1, "metadata": self.md1}, + {"id": self.id2, "values": self.vals2, "metadata": self.md2}, + ] + ) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) - ]) + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ] + ) ) def test_upsert_dictOfIdVecMD_UpsertVectorsWithoutMD(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert([{'id': self.id1, 'values': self.vals1}, - {'id': self.id2, 'values': self.vals2}]) + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert([{"id": self.id1, "values": self.vals1}, {"id": self.id2, "values": self.vals2}]) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1), - pinecone.Vector(id='vec2', values=self.vals2) - ]) + UpsertRequest(vectors=[Vector(id="vec1", values=self.vals1), Vector(id="vec2", values=self.vals2)]) ) def test_upsert_dictOfIdVecMD_UpsertVectorsWithSparseValues(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert([{'id': self.id1, 'values': self.vals1, 'sparse_values': self.sv1}, - {'id': self.id2, 'values': self.vals2, 'sparse_values': self.sv2}]) + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert( + [ + {"id": self.id1, "values": self.vals1, "sparse_values": self.sv1}, + {"id": self.id2, "values": self.vals2, "sparse_values": self.sv2}, + ] + ) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, sparse_values=SparseValues(**self.sv1)), - pinecone.Vector(id='vec2', values=self.vals2, sparse_values=SparseValues(**self.sv2)) - ]) + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, sparse_values=SparseValues(**self.sv1)), + Vector(id="vec2", values=self.vals2, sparse_values=SparseValues(**self.sv2)), + ] + ) ) def test_upsert_vectors_upsertInputVectors(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)], - namespace='ns') + mocker.patch.object(self.index._vector_api, "upsert", autospec=True) + self.index.upsert( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ) ) def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): - mocker.patch.object(Endpoint, '__call__', autospec=True) - chunks = [[pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], - [pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)]] - with pinecone.Index('example-index', pool_threads=30) as index: + chunks = [ + [Vector(id="vec1", values=self.vals1, metadata=self.md1)], + [Vector(id="vec2", values=self.vals2, metadata=self.md2)], + ] + with pinecone.Index("example-index", pool_threads=30) as index: + mocker.patch.object(index._vector_api, "upsert", autospec=True) + # Send requests in parallel async_results = [ - index.upsert(vectors=ids_vectors_chunk, namespace="ns", async_req=True) - for ids_vectors_chunk in chunks + index.upsert(vectors=ids_vectors_chunk, namespace="ns", async_req=True) for ids_vectors_chunk in chunks ] # Wait for and retrieve responses (this raises in case of error) [async_result.get() for async_result in async_results] - Endpoint.__call__.assert_any_call( - index._vector_api.upsert, - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - ], - namespace='ns'), - async_req=True + index._vector_api.upsert.assert_any_call( + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + ], + namespace="ns", + ), + async_req=True, ) - Endpoint.__call__.assert_any_call( - index._vector_api.upsert, - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - ], - namespace='ns'), - async_req=True + index._vector_api.upsert.assert_any_call( + UpsertRequest( + vectors=[ + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ), + async_req=True, ) def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index._vector_api, - 'upsert', - autospec=True, - side_effect=lambda upsert_request: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)], - namespace='ns', + mocker.patch.object( + self.index._vector_api, + "upsert", + autospec=True, + side_effect=lambda upsert_request: UpsertResponse(upserted_count=len(upsert_request.vectors)), + ) + + result = self.index.upsert( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", batch_size=1, - show_progress=False) + show_progress=False, + ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + ], + namespace="ns", + ) ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ) ) assert result.upserted_count == 2 def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index._vector_api, - 'upsert', - autospec=True, - side_effect=lambda upsert_request: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], - namespace='ns', - batch_size=2) + mocker.patch.object( + self.index._vector_api, + "upsert", + autospec=True, + side_effect=lambda upsert_request: UpsertResponse(upserted_count=len(upsert_request.vectors)), + ) + + 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), + ], + namespace="ns", + batch_size=2, + ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ) ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec3", values=self.vals1, metadata=self.md1), + ], + namespace="ns", + ) ) assert result.upserted_count == 3 def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index._vector_api, - 'upsert', - autospec=True, - side_effect=lambda upsert_request: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], - namespace='ns', - batch_size=5) + mocker.patch.object( + self.index._vector_api, + "upsert", + autospec=True, + side_effect=lambda upsert_request: UpsertResponse(upserted_count=len(upsert_request.vectors)), + ) + + 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), + ], + namespace="ns", + batch_size=5, + ) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), - ], namespace='ns') + 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), + ], + namespace="ns", + ) ) assert result.upserted_count == 3 def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object(self.index._vector_api, - 'upsert', - autospec=True, - side_effect=lambda upsert_request: UpsertResponse( - upserted_count=len(upsert_request.vectors))) - - result = self.index.upsert(vectors= - [('vec1', self.vals1, self.md1), - ('vec2', self.vals2, self.md2), - ('vec3', self.vals1, self.md1)], - namespace='ns', - batch_size=2) + mocker.patch.object( + self.index._vector_api, + "upsert", + autospec=True, + side_effect=lambda upsert_request: UpsertResponse(upserted_count=len(upsert_request.vectors)), + ) + + result = self.index.upsert( + vectors=[("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2), ("vec3", self.vals1, self.md1)], + namespace="ns", + batch_size=2, + ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ], + namespace="ns", + ) ) self.index._vector_api.upsert.assert_any_call( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), - ], namespace='ns') + UpsertRequest( + vectors=[ + Vector(id="vec3", values=self.vals1, metadata=self.md1), + ], + namespace="ns", + ) ) assert result.upserted_count == 3 def test_upsert_dataframe(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True, return_value=UpsertResponse(upserted_count=2)) - df = pd.DataFrame([ - {'id': self.id1, 'values': self.vals1, 'metadata': self.md1}, - {'id': self.id2, 'values': self.vals2, 'metadata': self.md2} - ]) + mocker.patch.object( + self.index._vector_api, "upsert", autospec=True, return_value=UpsertResponse(upserted_count=2) + ) + df = pd.DataFrame( + [ + {"id": self.id1, "values": self.vals1, "metadata": self.md1}, + {"id": self.id2, "values": self.vals2, "metadata": self.md2}, + ] + ) self.index.upsert_from_dataframe(df) self.index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), - pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) - ]) + UpsertRequest( + vectors=[ + Vector(id="vec1", values=self.vals1, metadata=self.md1), + Vector(id="vec2", values=self.vals2, metadata=self.md2), + ] + ) ) def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): - with pytest.raises(ValueError, match='batch_size must be a positive integer'): - self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], - namespace='ns', - batch_size=0) - - with pytest.raises(ValueError, match='batch_size must be a positive integer'): - self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], - namespace='ns', - batch_size=-1) + 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)], namespace="ns", batch_size=0 + ) + + 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)], + namespace="ns", + batch_size=-1, + ) def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): - with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): - self.index.upsert(vectors=[ - pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], - namespace='ns', + with pytest.raises(ValueError, match="async_req is not supported when batch_size is provided."): + self.index.upsert( + vectors=[Vector(id="vec1", values=self.vals1, metadata=self.md1)], + namespace="ns", batch_size=1, - async_req=True) + async_req=True, + ) # endregion # region: query tests def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): - response = QueryResponse(results=[], - matches=[ScoredVector(id="1", - score=0.9, - values=[0.0], - metadata={"a": 2})], - namespace="test") + response = QueryResponse( + results=[], matches=[ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], namespace="test" + ) - mocker.patch.object(self.index._vector_api, 'query', autospec=True, return_value=response) + mocker.patch.object(self.index._vector_api, "query", autospec=True, return_value=response) actual = self.index.query(top_k=10, vector=self.vals1) - self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, vector=self.vals1) + self.index._vector_api.query.assert_called_once_with(pinecone.QueryRequest(top_k=10, vector=self.vals1)) + expected = QueryResponse( + matches=[ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], namespace="test" ) - expected = QueryResponse(matches=[ScoredVector(id="1", - score=0.9, - values=[0.0], - metadata={"a": 2})], - namespace="test") - expected._data_store.pop('results', None) - assert actual == expected + assert expected.to_dict() == actual.to_dict() def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns') + mocker.patch.object(self.index._vector_api, "query", autospec=True) + self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns") self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns') + pinecone.QueryRequest(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns") ) def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, queries=[ - (self.vals1,), - (self.vals2,) - ]) + mocker.patch.object(self.index._vector_api, "query", autospec=True) + self.index.query(top_k=10, queries=[(self.vals1,), (self.vals2,)]) self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, queries=[ - pinecone.QueryVector(values=self.vals1), - pinecone.QueryVector(values=self.vals2) - ]) + pinecone.QueryRequest( + top_k=10, queries=[pinecone.QueryVector(values=self.vals1), pinecone.QueryVector(values=self.vals2)] + ) ) def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, queries=[ - (self.vals1, self.filter1), - (self.vals2, self.filter2) - ]) + mocker.patch.object(self.index._vector_api, "query", autospec=True) + self.index.query(top_k=10, queries=[(self.vals1, self.filter1), (self.vals2, self.filter2)]) self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, queries=[ - pinecone.QueryVector(values=self.vals1, filter=self.filter1), - pinecone.QueryVector(values=self.vals2, filter=self.filter2) - ]) + pinecone.QueryRequest( + top_k=10, + queries=[ + pinecone.QueryVector(values=self.vals1, filter=self.filter1), + pinecone.QueryVector(values=self.vals2, filter=self.filter2), + ], + ) ) def test_query_byVecId_queryByVecId(self, mocker): - mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, id='vec1', include_metadata=True, include_values=False) + mocker.patch.object(self.index._vector_api, "query", autospec=True) + self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, id='vec1', include_metadata=True, include_values=False) + pinecone.QueryRequest(top_k=10, id="vec1", include_metadata=True, include_values=False) ) # endregion @@ -364,60 +409,52 @@ def test_query_byVecId_queryByVecId(self, mocker): # region: delete tests def test_delete_byIds_deleteByIds(self, mocker): - mocker.patch.object(self.index._vector_api, 'delete', autospec=True) - self.index.delete(ids=['vec1', 'vec2']) - self.index._vector_api.delete.assert_called_once_with( - pinecone.DeleteRequest(ids=['vec1', 'vec2']) - ) + mocker.patch.object(self.index._vector_api, "delete", autospec=True) + self.index.delete(ids=["vec1", "vec2"]) + self.index._vector_api.delete.assert_called_once_with(pinecone.DeleteRequest(ids=["vec1", "vec2"])) def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'delete', autospec=True) - self.index.delete(delete_all=True, filter=self.filter1, namespace='ns') + mocker.patch.object(self.index._vector_api, "delete", autospec=True) + self.index.delete(delete_all=True, filter=self.filter1, namespace="ns") self.index._vector_api.delete.assert_called_once_with( - pinecone.DeleteRequest(delete_all=True, filter=self.filter1, namespace='ns') + pinecone.DeleteRequest(delete_all=True, filter=self.filter1, namespace="ns") ) def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'delete', autospec=True) + mocker.patch.object(self.index._vector_api, "delete", autospec=True) self.index.delete(delete_all=True) - self.index._vector_api.delete.assert_called_once_with( - pinecone.DeleteRequest(delete_all=True) - ) + self.index._vector_api.delete.assert_called_once_with(pinecone.DeleteRequest(delete_all=True)) # endregion # region: fetch tests def test_fetch_byIds_fetchByIds(self, mocker): - mocker.patch.object(self.index._vector_api, 'fetch', autospec=True) - self.index.fetch(ids=['vec1', 'vec2']) - self.index._vector_api.fetch.assert_called_once_with( - ids=['vec1', 'vec2'] - ) + mocker.patch.object(self.index._vector_api, "fetch", autospec=True) + self.index.fetch(ids=["vec1", "vec2"]) + self.index._vector_api.fetch.assert_called_once_with(ids=["vec1", "vec2"]) def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): - mocker.patch.object(self.index._vector_api, 'fetch', autospec=True) - self.index.fetch(ids=['vec1', 'vec2'], namespace='ns') - self.index._vector_api.fetch.assert_called_once_with( - ids=['vec1', 'vec2'], namespace='ns' - ) + mocker.patch.object(self.index._vector_api, "fetch", autospec=True) + self.index.fetch(ids=["vec1", "vec2"], namespace="ns") + self.index._vector_api.fetch.assert_called_once_with(ids=["vec1", "vec2"], namespace="ns") # endregion # region: update tests def test_update_byIdAnValues_updateByIdAndValues(self, mocker): - mocker.patch.object(self.index._vector_api, 'update', autospec=True) - self.index.update(id='vec1', values=self.vals1, namespace='ns') + mocker.patch.object(self.index._vector_api, "update", autospec=True) + self.index.update(id="vec1", values=self.vals1, namespace="ns") self.index._vector_api.update.assert_called_once_with( - pinecone.UpdateRequest(id='vec1', values=self.vals1, namespace='ns') + pinecone.UpdateRequest(id="vec1", values=self.vals1, namespace="ns") ) def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): - mocker.patch.object(self.index._vector_api, 'update', autospec=True) - self.index.update('vec1', values=self.vals1, metadata=self.md1) + mocker.patch.object(self.index._vector_api, "update", autospec=True) + self.index.update("vec1", values=self.vals1, metadata=self.md1) self.index._vector_api.update.assert_called_once_with( - pinecone.UpdateRequest(id='vec1', values=self.vals1, metadata=self.md1) + pinecone.UpdateRequest(id="vec1", values=self.vals1, metadata=self.md1) ) # endregion @@ -425,15 +462,15 @@ def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, moc # region: describe index tests def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'describe_index_stats', autospec=True) + 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( - DescribeIndexStatsRequest()) + self.index._vector_api.describe_index_stats.assert_called_once_with(DescribeIndexStatsRequest()) def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'describe_index_stats', autospec=True) + 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( - DescribeIndexStatsRequest(filter=self.filter1)) + DescribeIndexStatsRequest(filter=self.filter1) + ) # endregion diff --git a/tests/unit/test_manage.py b/tests/unit/test_manage.py index 70c7dedb2..0a65d67ce 100644 --- a/tests/unit/test_manage.py +++ b/tests/unit/test_manage.py @@ -27,7 +27,7 @@ def test_create_index_with_timeout(self, mocker, timeout_value, get_status_calls mocker.patch('pinecone.manage._get_status', side_effect=get_status_responses) mocker.patch('time.sleep') - pinecone.manage.create_index("my-index", 10, timeout=timeout_value) + pinecone.manage.create_index("my-index", 10, timeout=timeout_value, cloud="aws", region="us-west1", capacity_mode="pod") pinecone.manage._get_api_instance.assert_called_once() assert pinecone.manage._get_status.call_count == get_status_calls From 2981ab4efa53af8c8e52fe8176c2f9c6cdaaff82 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 20 Oct 2023 10:52:47 -0400 Subject: [PATCH 02/39] Config / init refactor for state encapsulation (#220) ## Problem Singleton config limits how people can use this SDK and makes testing more difficult. Also, we no longer should fetch projectId and construct data url out of configuration parts, to keep the client agnostic to the format of the data plane url. ## Solution - **State encapsulation using classes** - We want to encapsulate all config-related state into a new class `Config` and a subclass `PineconeConfig`. - `Config` is a vessel for api_key, host, and openapi configuration. It is host-agnostic because it is used by both the control plane (`Pinecone`) and the data plane (`Index`) - `PineconeConfig` is a convenience class to set the controller host for `Pinecone`. - New singleton store `IndexHostStore` means we won't make unnecessary and repetitious calls to describe_index if a user creates multiple `Index` instances referring to the same index. In the old paradigm, this was accomplished with a piece of global state storing off projectId. - **Modified class init for Index** - `Index` class constructor now requires host url instead of an index name. If you use the helper method on a `Pinecone` class instance to instantiate the object, it will manage fetching the host url for you. E.g. `p = Pinecone(api_key='foo'); index = p.Index('my-index')`. ```python # Old way import pinecone pinecone.init(api_key='foo') index = pinecone.Index('my-index') # New way from pinecone import Pinecone client = Pinecone(api_key='foo') index = client.Index('my-index') # New way (alternate, for data-plane only use case) from pinecone import Index index = Index(api_key='foo', host='https://data-url') ``` - **Moving things around** - `manage.py` got moved and renamed to `pinecone/control/pinecone.py`. The functions such as `create_index`, `describe_index`, etc that previously were top-level package exports relying on global state to access config information have been turned into class methods on a new `Pinecone` class defined in this file. - `pinecone/index.py` got moved to `pinecone/data/index.py`. The `pinecone/data` package is a home for all classes used to access the data plane. - Everything `grpc` related got shoved into `pinecone/data/grpc`. - GRPC mess in one place only. Utils that were grpc-related got pulled out of `pinecone/utils.py` and moved to `pinecone/data/grpc/utils.py`. - Leftover util junk moved into a `deprecated` package. Probably will be deleted soon. - **Breaking down big files into small files** - The file previously at `pinecone/index_grpc.py` to split up into many smaller files inside `pinecone/data/grpc/` package. - Remaining util functions in `pinecone/utils.py` got broken up into many smaller files in `pinecone/utils/` - **Fix existing tests** - Needed to adjust a lot of import statements and sometimes setup functions to get pre-existing tests running. ## Using it ```python # We're going to use a new Pinecone class instead of interacting directly with the package # namespace as in the past from pinecone import Pinecone # No more init() method p = Pinecone(api_key='foo') # Target an index index = p.Index('my-index') # Use data plane methods index.describe_index_stats() ``` **Mostly working** - `describe_index` (call succeeds but need to follow up on source_collection field, would ideally return different object for different capacity_modes) **Somewhat working**: - `create_index` (API call succeeds, but client blows up when response is not the expected shape) - `delete_index` (only when timeout=-1, since otherwise it has dependency on `list_indexes`) **Broken**: - `list_indexes` (response not expected shape) ## Type of Change - [x] New feature (non-breaking change which adds functionality) - [x] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] This change requires a documentation update ## Test Plan Automated tests will be expanded in a future PR. A bunch of code moved around to different files or got split from big files into small files and I want to merge this part of the change to unlock parallel work by Austin various follow-ups. --- pinecone/__init__.py | 18 +- pinecone/config.py | 260 -------------- pinecone/config/__init__.py | 2 + pinecone/config/config.py | 69 ++++ pinecone/config/logging.py | 8 + pinecone/config/openapi.py | 78 +++++ pinecone/config/pinecone_config.py | 10 + pinecone/control/index_host_store.py | 39 +++ .../control/models/collection_description.py | 7 + pinecone/control/models/index_description.py | 13 + pinecone/control/pinecone.py | 277 +++++++++++++++ .../core/client/api/index_operations_api.py | 18 +- pinecone/core/client/models/create_request.py | 2 +- .../core/client/models/index_meta_database.py | 2 +- pinecone/data/__init__.py | 2 + pinecone/{ => data}/grpc/__init__.py | 0 pinecone/data/grpc/base.py | 161 +++++++++ pinecone/data/grpc/config.py | 33 ++ pinecone/data/grpc/future.py | 34 ++ pinecone/{ => data}/grpc/index_grpc.py | 319 +----------------- .../grpc/protos/vector_column_service_pb2.py | 2 +- .../grpc/protos/vector_column_service_pb2.pyi | 2 +- .../protos/vector_column_service_pb2_grpc.py | 2 +- pinecone/{ => data}/grpc/retry.py | 2 +- pinecone/data/grpc/utils.py | 107 ++++++ pinecone/{ => data}/index.py | 48 +-- pinecone/deprecated/__init__.py | 1 + pinecone/deprecated/legacy_utils.py | 88 +++++ pinecone/exceptions.py | 4 + pinecone/manage.py | 300 ---------------- pinecone/utils/__init__.py | 141 +------- pinecone/utils/check_kwargs.py | 8 + pinecone/utils/constants.py | 11 +- pinecone/utils/deprecation_notice.py | 5 + pinecone/utils/environment.py | 8 + pinecone/utils/error_handling.py | 9 +- pinecone/utils/fix_tuple_length.py | 3 + pinecone/utils/user_agent.py | 10 + tests/unit/test_config.py | 237 +++---------- tests/unit/test_control.py | 66 ++++ tests/unit/test_grpc_index.py | 9 +- tests/unit/test_index.py | 9 +- tests/unit/test_manage.py | 54 --- 43 files changed, 1162 insertions(+), 1316 deletions(-) delete mode 100644 pinecone/config.py create mode 100644 pinecone/config/__init__.py create mode 100644 pinecone/config/config.py create mode 100644 pinecone/config/logging.py create mode 100644 pinecone/config/openapi.py create mode 100644 pinecone/config/pinecone_config.py create mode 100644 pinecone/control/index_host_store.py create mode 100644 pinecone/control/models/collection_description.py create mode 100644 pinecone/control/models/index_description.py create mode 100644 pinecone/control/pinecone.py create mode 100644 pinecone/data/__init__.py rename pinecone/{ => data}/grpc/__init__.py (100%) create mode 100644 pinecone/data/grpc/base.py create mode 100644 pinecone/data/grpc/config.py create mode 100644 pinecone/data/grpc/future.py rename pinecone/{ => data}/grpc/index_grpc.py (71%) rename pinecone/{ => data}/grpc/protos/vector_column_service_pb2.py (99%) rename pinecone/{ => data}/grpc/protos/vector_column_service_pb2.pyi (99%) rename pinecone/{ => data}/grpc/protos/vector_column_service_pb2_grpc.py (99%) rename pinecone/{ => data}/grpc/retry.py (99%) create mode 100644 pinecone/data/grpc/utils.py rename pinecone/{ => data}/index.py (95%) create mode 100644 pinecone/deprecated/__init__.py create mode 100644 pinecone/deprecated/legacy_utils.py delete mode 100644 pinecone/manage.py create mode 100644 pinecone/utils/check_kwargs.py create mode 100644 pinecone/utils/deprecation_notice.py create mode 100644 pinecone/utils/environment.py create mode 100644 pinecone/utils/fix_tuple_length.py create mode 100644 pinecone/utils/user_agent.py create mode 100644 tests/unit/test_control.py delete mode 100644 tests/unit/test_manage.py diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 8ade68bca..a614ff283 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -3,22 +3,10 @@ """ from .config import * from .exceptions import * -from .manage import * -from .index import * +from .control.pinecone import Pinecone +from .data.index import * try: - from .grpc.index_grpc import * + from .data.grpc.index_grpc import * except ImportError: pass # ignore for non-[grpc] installations - -# Kept for backwards-compatibility -UpsertResult = None -"""@private""" -DeleteResult = None -"""@private""" -QueryResult = None -"""@private""" -FetchResult = None -"""@private""" -InfoResult = None -"""@private""" diff --git a/pinecone/config.py b/pinecone/config.py deleted file mode 100644 index f4bc276c3..000000000 --- a/pinecone/config.py +++ /dev/null @@ -1,260 +0,0 @@ -import logging -import sys -from typing import NamedTuple, List -import os - -import certifi -import requests -import configparser -import socket - -from urllib3.connection import HTTPConnection - -from pinecone.core.client.exceptions import ApiKeyError -from pinecone.utils import warn_deprecated, check_kwargs -from pinecone.utils.constants import ( - CLIENT_VERSION, - PARENT_LOGGER_NAME, - DEFAULT_PARENT_LOGGER_LEVEL, - TCP_KEEPIDLE, - TCP_KEEPINTVL, - TCP_KEEPCNT, -) -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration - -__all__ = ["Config", "init"] - -_logger = logging.getLogger(__name__) -_parent_logger = logging.getLogger(PARENT_LOGGER_NAME) -_parent_logger.setLevel(DEFAULT_PARENT_LOGGER_LEVEL) - - -class ConfigBase(NamedTuple): - environment: str = "" - api_key: str = "" - project_name: str = "" - controller_host: str = "" - openapi_config: OpenApiConfiguration = None - - -class _CONFIG: - """ - - Order of configs to load: - - - configs specified explicitly in reset - - environment variables - - configs specified in the INI file - - default configs - """ - - def __init__(self): - self.reset() - - def validate(self): - if not self._config.api_key: # None or empty string invalid - raise ApiKeyError("You haven't specified an Api-Key.") - - def reset(self, config_file=None, **kwargs): - config = ConfigBase() - - # Load config from file - file_config = self._load_config_file(config_file) - - # Get the environment first. Make sure that it is not overwritten in subsequent config objects. - environment = ( - kwargs.pop("environment", None) - or os.getenv("PINECONE_ENVIRONMENT") - or file_config.pop("environment", None) - or "us-west1-gcp" - ) - config = config._replace(environment=environment) - - # Set default config - default_config = ConfigBase( - controller_host="https://controller.{0}.pinecone.io".format(config.environment), - ) - config = config._replace(**self._preprocess_and_validate_config(default_config._asdict())) - - # Set INI file config - config = config._replace(**self._preprocess_and_validate_config(file_config)) - - # Set environment config - env_config = ConfigBase( - project_name=os.getenv("PINECONE_PROJECT_NAME"), - api_key=os.getenv("PINECONE_API_KEY"), - controller_host=os.getenv("PINECONE_CONTROLLER_HOST"), - ) - config = config._replace(**self._preprocess_and_validate_config(env_config._asdict())) - - # Set explicit config - config = config._replace(**self._preprocess_and_validate_config(kwargs)) - - self._config = config - - # Set OpenAPI client config - default_openapi_config = OpenApiConfiguration.get_default_copy() - default_openapi_config.ssl_ca_cert = certifi.where() - openapi_config = kwargs.pop("openapi_config", None) or default_openapi_config - - openapi_config.socket_options = self._get_socket_options() - - config = config._replace(openapi_config=openapi_config) - self._config = config - - def _preprocess_and_validate_config(self, config: dict) -> dict: - """Normalize, filter, and validate config keys/values. - - Trims whitespace, removes invalid keys (and the "environment" key), - and raises ValueError in case an invalid value was specified. - """ - # general preprocessing and filtering - result = {k: v for k, v in config.items() if k in ConfigBase._fields if v is not None} - result.pop("environment", None) - # validate api key - api_key = result.get("api_key") - # if api_key: - # try: - # uuid.UUID(api_key) - # except ValueError as e: - # raise ValueError(f"Pinecone API key \"{api_key}\" appears invalid. " - # f"Did you specify it correctly?") from e - return result - - def _load_config_file(self, config_file: str) -> dict: - """Load from INI config file.""" - config_obj = {} - if config_file: - full_path = os.path.expanduser(config_file) - if os.path.isfile(full_path): - parser = configparser.ConfigParser() - parser.read(full_path) - if "default" in parser.sections(): - config_obj = {**parser["default"]} - return config_obj - - @staticmethod - def _get_socket_options( - do_keep_alive: bool = True, - keep_alive_idle_sec: int = TCP_KEEPIDLE, - keep_alive_interval_sec: int = TCP_KEEPINTVL, - keep_alive_tries: int = TCP_KEEPCNT, - ) -> List[tuple]: - """ - Returns the socket options to pass to OpenAPI's Rest client - Args: - do_keep_alive: Whether to enable TCP keep alive mechanism - keep_alive_idle_sec: Time in seconds of connection idleness before starting to send keep alive probes - keep_alive_interval_sec: Interval time in seconds between keep alive probe messages - keep_alive_tries: Number of failed keep alive tries (unanswered KA messages) before terminating the connection - - Returns: - A list of socket options for the Rest client's connection pool - """ - # Source: https://www.finbourne.com/blog/the-mysterious-hanging-client-tcp-keep-alives - - socket_params = HTTPConnection.default_socket_options - if not do_keep_alive: - return socket_params - - socket_params += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] - - # TCP Keep Alive Probes for different platforms - platform = sys.platform - # TCP Keep Alive Probes for Linux - if ( - platform == "linux" - and hasattr(socket, "TCP_KEEPIDLE") - and hasattr(socket, "TCP_KEEPINTVL") - and hasattr(socket, "TCP_KEEPCNT") - ): - socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, keep_alive_idle_sec)] - socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, keep_alive_interval_sec)] - socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, keep_alive_tries)] - - # TCP Keep Alive Probes for Windows OS - # NOTE: Changing TCP KA params on windows is done via a different mechanism which OpenAPI's Rest client doesn't expose. - # Since the default values work well, it seems setting `(socket.SO_KEEPALIVE, 1)` is sufficient. - # Leaving this code here for future reference. - # elif platform == 'win32' and hasattr(socket, "SIO_KEEPALIVE_VALS"): - # socket.ioctl((socket.SIO_KEEPALIVE_VALS, (1, keep_alive_idle_sec * 1000, keep_alive_interval_sec * 1000))) - - # TCP Keep Alive Probes for Mac OS - elif platform == "darwin": - TCP_KEEPALIVE = 0x10 - socket_params += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, keep_alive_interval_sec)] - - return socket_params - - @property - def ENVIRONMENT(self): - return self._config.environment - - @property - def API_KEY(self): - return self._config.api_key - - @property - def PROJECT_NAME(self): - return self._config.project_name - - @property - def CONTROLLER_HOST(self): - return self._config.controller_host - - @property - def OPENAPI_CONFIG(self): - return self._config.openapi_config - - @property - def LOG_LEVEL(self): - """ - Deprecated since v2.0.2 [Will be removed in v3.0.0]; use the standard logging module logger "pinecone" instead. - """ - warn_deprecated( - description='LOG_LEVEL is deprecated. Use the standard logging module logger "pinecone" instead.', - deprecated_in="2.0.2", - removal_in="3.0.0", - ) - return logging.getLevelName(logging.getLogger("pinecone").level) - - -def init( - api_key: str = None, - host: str = None, - environment: str = None, - log_level: str = None, - openapi_config: OpenApiConfiguration = None, - config: str = "~/.pinecone", - **kwargs -): - """Initializes the Pinecone client. - - :param api_key: Required if not set in config file or by environment variable ``PINECONE_API_KEY``. - :param host: Optional. Controller host. - :param environment: Optional. Deployment environment. - :param openapi_config: Optional. Set OpenAPI client configuration. - :param config: Optional. An INI configuration file. - :param log_level: Deprecated since v2.0.2 [Will be removed in v3.0.0]; use the standard logging module to manage logger "pinecone" instead. - """ - check_kwargs(init, kwargs) - Config.reset( - api_key=api_key, - controller_host=host, - environment=environment, - openapi_config=openapi_config, - config_file=config, - **kwargs - ) - if log_level: - warn_deprecated( - description='log_level is deprecated. Use the standard logging module to manage logger "pinecone" instead.', - deprecated_in="2.0.2", - removal_in="3.0.0", - ) - - -Config = _CONFIG() - -# Init -init() diff --git a/pinecone/config/__init__.py b/pinecone/config/__init__.py new file mode 100644 index 000000000..42784d1ed --- /dev/null +++ b/pinecone/config/__init__.py @@ -0,0 +1,2 @@ +from .config import Config +from .pinecone_config import PineconeConfig diff --git a/pinecone/config/config.py b/pinecone/config/config.py new file mode 100644 index 000000000..886d01b5e --- /dev/null +++ b/pinecone/config/config.py @@ -0,0 +1,69 @@ +from typing import NamedTuple +import os + +from pinecone.utils import check_kwargs +from pinecone.exceptions import PineconeConfigurationError +from pinecone.core.client.exceptions import ApiKeyError +from pinecone.config.openapi import OpenApiConfigFactory +from pinecone.core.client.configuration import Configuration as OpenApiConfiguration + + +class ConfigBase(NamedTuple): + api_key: str = "" + host: str = "" + openapi_config: OpenApiConfiguration = None + + +class Config: + """ + + Configurations are resolved in the following order: + + - configs passed as keyword parameters + - configs specified in environment variables + - default values (if applicable) + """ + + """Initializes the Pinecone client. + + :param api_key: Required if not set in config file or by environment variable ``PINECONE_API_KEY``. + :param host: Optional. Controller host. + :param openapi_config: Optional. Set OpenAPI client configuration. + """ + + def __init__( + self, + api_key: str = None, + host: str = None, + openapi_config: OpenApiConfiguration = None, + **kwargs, + ): + api_key = api_key or kwargs.pop("api_key", None) or os.getenv("PINECONE_API_KEY") + host = host or kwargs.pop("host", None) + openapi_config = ( + openapi_config + or kwargs.pop("openapi_config", None) + or OpenApiConfigFactory.build(api_key=api_key, host=host) + ) + + check_kwargs(self.__init__, kwargs) + self._config = ConfigBase(api_key, host, openapi_config) + self.validate() + + def validate(self): + if not self._config.api_key: + raise PineconeConfigurationError("You haven't specified an Api-Key.") + if not self._config.host: + raise PineconeConfigurationError("You haven't specified a host.") + + @property + def API_KEY(self): + return self._config.api_key + + @property + def HOST(self): + return self._config.host + + @property + def OPENAPI_CONFIG(self): + return self._config.openapi_config diff --git a/pinecone/config/logging.py b/pinecone/config/logging.py new file mode 100644 index 000000000..51c788553 --- /dev/null +++ b/pinecone/config/logging.py @@ -0,0 +1,8 @@ +import logging + +PARENT_LOGGER_NAME = "pinecone" +DEFAULT_PARENT_LOGGER_LEVEL = "ERROR" + +_logger = logging.getLogger(__name__) +_parent_logger = logging.getLogger(PARENT_LOGGER_NAME) +_parent_logger.setLevel(DEFAULT_PARENT_LOGGER_LEVEL) diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py new file mode 100644 index 000000000..952a672de --- /dev/null +++ b/pinecone/config/openapi.py @@ -0,0 +1,78 @@ +import sys +from typing import List + +import certifi +import requests +import socket + +from urllib3.connection import HTTPConnection + +from pinecone.core.client.configuration import Configuration as OpenApiConfiguration + +TCP_KEEPINTVL = 60 # Sec +TCP_KEEPIDLE = 300 # Sec +TCP_KEEPCNT = 4 + + +class OpenApiConfigFactory: + @classmethod + def build(cls, api_key: str, host: str = None, **kwargs): + openapi_config = OpenApiConfiguration.get_default() + openapi_config.host = host + openapi_config.ssl_ca_cert = certifi.where() + openapi_config.socket_options = cls._get_socket_options() + openapi_config.api_key = {"ApiKeyAuth": api_key} + return openapi_config + + @classmethod + def _get_socket_options( + do_keep_alive: bool = True, + keep_alive_idle_sec: int = TCP_KEEPIDLE, + keep_alive_interval_sec: int = TCP_KEEPINTVL, + keep_alive_tries: int = TCP_KEEPCNT, + ) -> List[tuple]: + """ + Returns the socket options to pass to OpenAPI's Rest client + Args: + do_keep_alive: Whether to enable TCP keep alive mechanism + keep_alive_idle_sec: Time in seconds of connection idleness before starting to send keep alive probes + keep_alive_interval_sec: Interval time in seconds between keep alive probe messages + keep_alive_tries: Number of failed keep alive tries (unanswered KA messages) before terminating the connection + + Returns: + A list of socket options for the Rest client's connection pool + """ + # Source: https://www.finbourne.com/blog/the-mysterious-hanging-client-tcp-keep-alives + + socket_params = HTTPConnection.default_socket_options + if not do_keep_alive: + return socket_params + + socket_params += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] + + # TCP Keep Alive Probes for different platforms + platform = sys.platform + # TCP Keep Alive Probes for Linux + if ( + platform == "linux" + and hasattr(socket, "TCP_KEEPIDLE") + and hasattr(socket, "TCP_KEEPINTVL") + and hasattr(socket, "TCP_KEEPCNT") + ): + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, keep_alive_idle_sec)] + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, keep_alive_interval_sec)] + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, keep_alive_tries)] + + # TCP Keep Alive Probes for Windows OS + # NOTE: Changing TCP KA params on windows is done via a different mechanism which OpenAPI's Rest client doesn't expose. + # Since the default values work well, it seems setting `(socket.SO_KEEPALIVE, 1)` is sufficient. + # Leaving this code here for future reference. + # elif platform == 'win32' and hasattr(socket, "SIO_KEEPALIVE_VALS"): + # socket.ioctl((socket.SIO_KEEPALIVE_VALS, (1, keep_alive_idle_sec * 1000, keep_alive_interval_sec * 1000))) + + # TCP Keep Alive Probes for Mac OS + elif platform == "darwin": + TCP_KEEPALIVE = 0x10 + socket_params += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, keep_alive_interval_sec)] + + return socket_params diff --git a/pinecone/config/pinecone_config.py b/pinecone/config/pinecone_config.py new file mode 100644 index 000000000..64f879a81 --- /dev/null +++ b/pinecone/config/pinecone_config.py @@ -0,0 +1,10 @@ +import os +from .config import Config + +DEFAULT_CONTROLLER_HOST = "https://api.pinecone.io" + + +class PineconeConfig(Config): + def __init__(self, api_key: str = None, host: str = None, **kwargs): + host = host or kwargs.get("host") or os.getenv("PINECONE_CONTROLLER_HOST") or DEFAULT_CONTROLLER_HOST + super().__init__(api_key=api_key, host=host, **kwargs) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py new file mode 100644 index 000000000..efe9ea5d4 --- /dev/null +++ b/pinecone/control/index_host_store.py @@ -0,0 +1,39 @@ +from pinecone.config import Config +from pinecone.core.client.api.index_operations_api import IndexOperationsApi + + +class SingletonMeta(type): + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + instance = super().__call__(*args, **kwargs) + cls._instances[cls] = instance + return cls._instances[cls] + + +class IndexHostStore(metaclass=SingletonMeta): + def __init__(self): + self._indexHosts = {} + + def _key(self, config: Config, index_name: str) -> str: + return ":".join([config.API_KEY, index_name]) + + def delete_host(self, config: Config, index_name: str): + key = self._key(config, index_name) + if key in self._indexHosts: + del self._indexHosts[key] + + def set_host(self, config: Config, index_name: str, host: str): + if host: + key = self._key(config, index_name) + self._indexHosts[key] = "https://" + host + + def get_host(self, api: IndexOperationsApi, config: Config, index_name: str) -> str: + key = self._key(config, index_name) + if key in self._indexHosts: + return self._indexHosts[key] + else: + description = api.describe_index(index_name) + self.set_host(config, index_name, description.status.host) + return self._indexHosts[key] diff --git a/pinecone/control/models/collection_description.py b/pinecone/control/models/collection_description.py new file mode 100644 index 000000000..ff3f4b41a --- /dev/null +++ b/pinecone/control/models/collection_description.py @@ -0,0 +1,7 @@ +class CollectionDescription(object): + def __init__(self, keys, values): + for k, v in zip(keys, values): + self.__dict__[k] = v + + def __str__(self): + return str(self.__dict__) diff --git a/pinecone/control/models/index_description.py b/pinecone/control/models/index_description.py new file mode 100644 index 000000000..e86ffbd59 --- /dev/null +++ b/pinecone/control/models/index_description.py @@ -0,0 +1,13 @@ +from typing import NamedTuple + + +class IndexDescription(NamedTuple): + name: str + metric: str + replicas: int + dimension: int + shards: int + pods: int + pod_type: str + status: None + metadata_config: None diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py new file mode 100644 index 000000000..c6d3037b0 --- /dev/null +++ b/pinecone/control/pinecone.py @@ -0,0 +1,277 @@ +import time +from typing import Optional + +from .index_host_store import IndexHostStore + +from pinecone.config import PineconeConfig, Config + +from pinecone.control.models.index_description import IndexDescription +from pinecone.control.models.collection_description import CollectionDescription + +from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api_client import ApiClient +from pinecone.core.client.models.create_request import CreateRequest +from pinecone.core.client.models.patch_request import PatchRequest +from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.utils import get_user_agent + +from pinecone.data import Index +from pinecone.data import GRPCIndex + + +class Pinecone: + def __init__( + self, + api_key: str = None, + host: str = None, + config: Config = None, + index_api: IndexOperationsApi = None, + **kwargs, + ): + if config or kwargs.get("config"): + self.config = config or kwargs.get("config") + else: + self.config = PineconeConfig(api_key=api_key, host=host, **kwargs) + + if index_api: + self.index_api = index_api + else: + api_client = ApiClient(configuration=self.config.OPENAPI_CONFIG) + api_client.user_agent = get_user_agent() + self.index_api = IndexOperationsApi(api_client) + + self.index_host_store = IndexHostStore() + + def create_index( + self, + name: str, + dimension: int, + cloud: str, + region: str, + capacity_mode: str, + timeout: int = None, + index_type: str = "approximated", + metric: str = "cosine", + replicas: int = 1, + shards: int = 1, + pods: int = 1, + pod_type: str = "p1", + index_config: dict = None, + metadata_config: dict = None, + source_collection: str = "", + ): + """Creates a Pinecone index. + + :param name: the name of the index. + :type name: str + :param dimension: the dimension of vectors that would be inserted in the index + :param cloud: The cloud where you would like your index hosted. One of `{"aws", "gcp"}`. + :param region: The region where you would like your index hosted. + :param capacity_mode: The capacity mode for the index. One of `{"pod"}`. + :param index_type: type of index, one of `{"approximated", "exact"}`, defaults to "approximated". + The "approximated" index uses fast approximate search algorithms developed by Pinecone. + The "exact" index uses accurate exact search algorithms. + It performs exhaustive searches and thus it is usually slower than the "approximated" index. + :type index_type: str, optional + :param metric: type of metric used in the vector index, one of `{"cosine", "dotproduct", "euclidean"}`, defaults to "cosine". + Use "cosine" for cosine similarity, + "dotproduct" for dot-product, + and "euclidean" for euclidean distance. + :type metric: str, optional + :param replicas: the number of replicas, defaults to 1. + Use at least 2 replicas if you need high availability (99.99% uptime) for querying. + For additional throughput (QPS) your index needs to support, provision additional replicas. + :type replicas: int, optional + :param shards: the number of shards per index, defaults to 1. + Use 1 shard per 1GB of vectors + :type shards: int,optional + :param pods: Total number of pods to be used by the index. pods = shard*replicas + :type pods: int,optional + :param pod_type: the pod type to be used for the index. can be one of p1 or s1. + :type pod_type: str,optional + :param index_config: Advanced configuration options for the index + :param metadata_config: Configuration related to the metadata index + :type metadata_config: dict, optional + :param source_collection: Collection name to create the index from + :type metadata_config: str, optional + :type timeout: int, optional + :param timeout: Timeout for 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 + """ + api_instance = self.index_api + + api_instance.create_index( + create_request=CreateRequest( + name=name, + dimension=dimension, + cloud=cloud, + region=region, + capacity_mode=capacity_mode, + index_type=index_type, + metric=metric, + replicas=replicas, + shards=shards, + pods=pods, + pod_type=pod_type, + index_config=index_config or {}, + metadata_config=metadata_config, + source_collection=source_collection, + ) + ) + + def is_ready(): + status = self._get_status(name) + ready = status["ready"] + return ready + + if timeout == -1: + return + if timeout is None: + while not is_ready(): + time.sleep(5) + else: + while (not is_ready()) and timeout >= 0: + time.sleep(5) + timeout -= 5 + if timeout and timeout < 0: + raise ( + TimeoutError( + "Please call the describe_index API ({}) to confirm index status.".format( + "https://www.pinecone.io/docs/api/operation/describe_index/" + ) + ) + ) + + def delete_index(self, name: str, timeout: int = None): + """Deletes a Pinecone index. + + :param name: the name of the index. + :type name: str + :param timeout: Timeout for 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 + :type timeout: int, optional + """ + api_instance = self.index_api + api_instance.delete_index(name) + self.index_host_store.delete_host(self.config, name) + + def get_remaining(): + return name in api_instance.list_indexes() + + if timeout == -1: + return + + if timeout is None: + while get_remaining(): + time.sleep(5) + else: + while get_remaining() and timeout >= 0: + time.sleep(5) + timeout -= 5 + if timeout and timeout < 0: + raise ( + TimeoutError( + "Please call the list_indexes API ({}) to confirm if index is deleted".format( + "https://www.pinecone.io/docs/api/operation/list_indexes/" + ) + ) + ) + + def list_indexes(self): + """Lists all indexes.""" + response = self.index_api.list_indexes() + return response + + def describe_index(self, name: str): + """Describes a Pinecone index. + + :param name: the name of the index to describe. + :return: Returns an `IndexDescription` object + """ + api_instance = self.index_api + response = api_instance.describe_index(name) + db = response.database + host = response.status.host + + self.index_host_store.set_host(self.config, name, host) + + return IndexDescription( + name=db.name, + metric=db.metric, + replicas=db.replicas, + dimension=db.dimension, + shards=db.shards, + pods=db.pods, + pod_type=db.pod_type, + status=response.status, + metadata_config=db.metadata_config, + ) + + def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: Optional[str] = ""): + """Changes current configuration of the 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. + """ + api_instance = self.index_api + config_args = {} + if pod_type != "": + config_args.update(pod_type=pod_type) + if replicas: + config_args.update(replicas=replicas) + patch_request = PatchRequest(**config_args) + api_instance.configure_index(name, patch_request=patch_request) + + def scale_index(self, name: str, replicas: int): + """Increases number of replicas for the index. + + :param name: the name of the Index + :type name: str + :param replicas: the number of replicas in the index now, lowest value is 0. + :type replicas: int + """ + api_instance = self.index_api + api_instance.configure_index(name, patch_request=PatchRequest(replicas=replicas, pod_type="")) + + def create_collection(self, name: str, source: str): + """Create a collection + :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): + """List all collections""" + api_instance = self.index_api + response = api_instance.list_collections() + return response + + def delete_collection(self, name: str): + """Deletes a collection. + :param: name: The name of the collection + """ + 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 + """ + api_instance = self.index_api + response = api_instance.describe_collection(name).to_dict() + response_object = CollectionDescription(response.keys(), response.values()) + return response_object + + def _get_status(self, name: str): + api_instance = self.index_api + response = api_instance.describe_index(name) + return response["status"] + + def Index(self, name: str): + index_host = self.index_host_store.get_host(self.index_api, self.config, name) + return Index(api_key=self.config.API_KEY, host=index_host) + + def GRPCIndex(self, name: str): + return GRPCIndex(self.config, name) diff --git a/pinecone/core/client/api/index_operations_api.py b/pinecone/core/client/api/index_operations_api.py index 5c33010fc..52f581780 100644 --- a/pinecone/core/client/api/index_operations_api.py +++ b/pinecone/core/client/api/index_operations_api.py @@ -134,7 +134,7 @@ def configure_index_with_http_info( :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -294,7 +294,7 @@ def create_collection_with_http_info( :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -450,7 +450,7 @@ def create_index_with_http_info( :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -608,7 +608,7 @@ def delete_collection_with_http_info( :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -757,7 +757,7 @@ def delete_index_with_http_info( :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -906,7 +906,7 @@ def describe_collection_with_http_info( :rtype: tuple(CollectionMeta, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -1055,7 +1055,7 @@ def describe_index_with_http_info( :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -1196,7 +1196,7 @@ def list_collections_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E50 :rtype: tuple(List[str], status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) @@ -1335,7 +1335,7 @@ def list_indexes_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :rtype: tuple(ListIndexes200Response, status_code(int), headers(HTTPHeaderDict)) """ - _hosts = ["https://controller.{environment}.pinecone.io"] + _hosts = ["https://api.pinecone.io"] _host = _hosts[0] if kwargs.get("_host_index"): _host_index = int(kwargs.get("_host_index")) diff --git a/pinecone/core/client/models/create_request.py b/pinecone/core/client/models/create_request.py index 9c6c95170..87bedfd3a 100644 --- a/pinecone/core/client/models/create_request.py +++ b/pinecone/core/client/models/create_request.py @@ -35,7 +35,7 @@ class CreateRequest(BaseModel): dimension: StrictInt = Field(..., description="The dimensions of the vectors to be inserted in the index") region: StrictStr = Field(..., description="The region where you would like your index to be created") cloud: StrictStr = Field(..., description="The public cloud where you would like your index hosted") - capacity_mode: StrictStr = Field(..., description="The capacity mode for the index") + capacity_mode: StrictStr = Field(..., description="The capacity mode for the index.") index_type: Optional[StrictStr] = Field( "approximated", description="The type of vector index. Pinecone supports 'approximated'." ) diff --git a/pinecone/core/client/models/index_meta_database.py b/pinecone/core/client/models/index_meta_database.py index ba1af18eb..7d0970e1d 100644 --- a/pinecone/core/client/models/index_meta_database.py +++ b/pinecone/core/client/models/index_meta_database.py @@ -30,7 +30,7 @@ class IndexMetaDatabase(BaseModel): """ name: StrictStr = Field(...) - dimension: StrictStr = Field(...) + dimension: StrictInt = Field(...) capacity_mode: StrictStr = Field(...) index_type: Optional[StrictStr] = None metric: StrictStr = Field(...) diff --git a/pinecone/data/__init__.py b/pinecone/data/__init__.py new file mode 100644 index 000000000..7d4f066ef --- /dev/null +++ b/pinecone/data/__init__.py @@ -0,0 +1,2 @@ +from .index import Index +from .grpc.index_grpc import GRPCIndex \ No newline at end of file diff --git a/pinecone/grpc/__init__.py b/pinecone/data/grpc/__init__.py similarity index 100% rename from pinecone/grpc/__init__.py rename to pinecone/data/grpc/__init__.py diff --git a/pinecone/data/grpc/base.py b/pinecone/data/grpc/base.py new file mode 100644 index 000000000..3452f5962 --- /dev/null +++ b/pinecone/data/grpc/base.py @@ -0,0 +1,161 @@ +import logging +from abc import ABC, abstractmethod +from functools import wraps +from typing import NamedTuple, Optional, Dict + +import certifi +import grpc +from grpc._channel import _InactiveRpcError +import json + +from .retry import RetryConfig + +from pinecone import Config +from .utils import _generate_request_id +from .config import GRPCClientConfig +from pinecone.utils.constants import MAX_MSG_SIZE, REQUEST_ID, CLIENT_VERSION +from pinecone.exceptions import PineconeException + +_logger = logging.getLogger(__name__) + +class GRPCIndexBase(ABC): + """ + Base class for grpc-based interaction with Pinecone indexes + """ + + _pool = None + + def __init__( + self, + index_name: str, + config: Config, + channel=None, + grpc_config: GRPCClientConfig = None, + _endpoint_override: str = None, + ): + self.name = index_name + + self.grpc_client_config = grpc_config or GRPCClientConfig() + self.retry_config = self.grpc_client_config.retry_config or RetryConfig() + self.fixed_metadata = {"api-key": config.API_KEY, "service-name": index_name, "client-version": CLIENT_VERSION} + self._endpoint_override = _endpoint_override + + self.method_config = json.dumps( + { + "methodConfig": [ + { + "name": [{"service": "VectorService.Upsert"}], + "retryPolicy": { + "maxAttempts": 5, + "initialBackoff": "0.1s", + "maxBackoff": "1s", + "backoffMultiplier": 2, + "retryableStatusCodes": ["UNAVAILABLE"], + }, + }, + { + "name": [{"service": "VectorService"}], + "retryPolicy": { + "maxAttempts": 5, + "initialBackoff": "0.1s", + "maxBackoff": "1s", + "backoffMultiplier": 2, + "retryableStatusCodes": ["UNAVAILABLE"], + }, + }, + ] + } + ) + + self._channel = channel or self._gen_channel() + self.stub = self.stub_class(self._channel) + + @property + @abstractmethod + def stub_class(self): + pass + + def _endpoint(self): + return ( + self._endpoint_override + if self._endpoint_override + else f"{self.name}-{Config.PROJECT_NAME}.svc.{Config.ENVIRONMENT}.pinecone.io:443" + ) + + def _gen_channel(self, options=None): + target = self._endpoint() + default_options = { + "grpc.max_send_message_length": MAX_MSG_SIZE, + "grpc.max_receive_message_length": MAX_MSG_SIZE, + "grpc.service_config": self.method_config, + "grpc.enable_retries": True, + } + if self.grpc_client_config.secure: + default_options["grpc.ssl_target_name_override"] = target.split(":")[0] + user_provided_options = options or {} + _options = tuple((k, v) for k, v in {**default_options, **user_provided_options}.items()) + _logger.debug( + "creating new channel with endpoint %s options %s and config %s", target, _options, self.grpc_client_config + ) + if not self.grpc_client_config.secure: + channel = grpc.insecure_channel(target, options=_options) + else: + root_cas = open(certifi.where(), "rb").read() + tls = grpc.ssl_channel_credentials(root_certificates=root_cas) + channel = grpc.secure_channel(target, tls, options=_options) + + return channel + + @property + def channel(self): + """Creates GRPC channel.""" + if self.grpc_client_config.reuse_channel and self._channel and self.grpc_server_on(): + return self._channel + self._channel = self._gen_channel() + return self._channel + + def grpc_server_on(self) -> bool: + try: + grpc.channel_ready_future(self._channel).result(timeout=self.grpc_client_config.conn_timeout) + return True + except grpc.FutureTimeoutError: + return False + + def close(self): + """Closes the connection to the index.""" + try: + self._channel.close() + except TypeError: + pass + + def _wrap_grpc_call( + self, func, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None + ): + @wraps(func) + def wrapped(): + user_provided_metadata = metadata or {} + _metadata = tuple( + (k, v) for k, v in {**self.fixed_metadata, **self._request_metadata(), **user_provided_metadata}.items() + ) + try: + return func( + request, + timeout=timeout, + metadata=_metadata, + credentials=credentials, + wait_for_ready=wait_for_ready, + compression=compression, + ) + except _InactiveRpcError as e: + raise PineconeException(e._state.debug_error_string) from e + + return wrapped() + + def _request_metadata(self) -> Dict[str, str]: + return {REQUEST_ID: _generate_request_id()} + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() diff --git a/pinecone/data/grpc/config.py b/pinecone/data/grpc/config.py new file mode 100644 index 000000000..13ab7dae3 --- /dev/null +++ b/pinecone/data/grpc/config.py @@ -0,0 +1,33 @@ +from .retry import RetryConfig +from typing import NamedTuple, Optional, Dict + + +class GRPCClientConfig(NamedTuple): + """ + GRPC client configuration options. + + :param secure: Whether to use encrypted protocol (SSL). defaults to True. + :type traceroute: bool, optional + :param timeout: defaults to 2 seconds. Fail if gateway doesn't receive response within timeout. + :type timeout: int, optional + :param conn_timeout: defaults to 1. Timeout to retry connection if gRPC is unavailable. 0 is no retry. + :type conn_timeout: int, optional + :param reuse_channel: Whether to reuse the same grpc channel for multiple requests + :type reuse_channel: bool, optional + :param retry_config: RetryConfig indicating how requests should be retried + :type retry_config: RetryConfig, optional + :param grpc_channel_options: A dict of gRPC channel arguments + :type grpc_channel_options: Dict[str, str] + """ + + secure: bool = True + timeout: int = 20 + conn_timeout: int = 1 + reuse_channel: bool = True + retry_config: Optional[RetryConfig] = None + grpc_channel_options: Dict[str, str] = None + + @classmethod + def _from_dict(cls, kwargs: dict): + cls_kwargs = {kk: vv for kk, vv in kwargs.items() if kk in cls._fields} + return cls(**cls_kwargs) diff --git a/pinecone/data/grpc/future.py b/pinecone/data/grpc/future.py new file mode 100644 index 000000000..160169d67 --- /dev/null +++ b/pinecone/data/grpc/future.py @@ -0,0 +1,34 @@ +from grpc._channel import _MultiThreadedRendezvous +from pinecone.exceptions import PineconeException + + +class PineconeGrpcFuture: + def __init__(self, delegate): + self._delegate = delegate + + def cancel(self): + return self._delegate.cancel() + + def cancelled(self): + return self._delegate.cancelled() + + def running(self): + return self._delegate.running() + + def done(self): + return self._delegate.done() + + def add_done_callback(self, fun): + return self._delegate.add_done_callback(fun) + + def result(self, timeout=None): + try: + return self._delegate.result(timeout=timeout) + except _MultiThreadedRendezvous as e: + raise PineconeException(e._state.debug_error_string) from e + + def exception(self, timeout=None): + return self._delegate.exception(timeout=timeout) + + def traceback(self, timeout=None): + return self._delegate.traceback(timeout=timeout) diff --git a/pinecone/grpc/index_grpc.py b/pinecone/data/grpc/index_grpc.py similarity index 71% rename from pinecone/grpc/index_grpc.py rename to pinecone/data/grpc/index_grpc.py index 1e35300ba..ef6e23db0 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/data/grpc/index_grpc.py @@ -1,22 +1,19 @@ import logging import numbers -from abc import ABC, abstractmethod -from functools import wraps -from importlib.util import find_spec -from typing import NamedTuple, Optional, Dict, Iterable, Union, List, Tuple, Any +from typing import Optional, Dict, Iterable, Union, List, Tuple, Any from collections.abc import Mapping -import certifi -import grpc from google.protobuf import json_format -from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous + from tqdm.autonotebook import tqdm -import json -from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, DescribeIndexStatsResponse -from pinecone.config import Config -from pinecone.core.client.models.namespace_summary import NamespaceSummary -from pinecone.core.client.models.vector import Vector as _Vector +from .utils import dict_to_proto_struct, parse_fetch_response, parse_query_response, parse_stats_response + +from pinecone.core.client.models import ( + FetchResponse, + QueryResponse, + DescribeIndexStatsResponse, +) from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector as GRPCVector, QueryVector as GRPCQueryVector, @@ -31,311 +28,21 @@ UpdateResponse, SparseValues as GRPCSparseValues, ) -from pinecone.core.client.models.sparse_values import SparseValues from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub -from pinecone.grpc.retry import RetryOnRpcErrorClientInterceptor, RetryConfig -from pinecone.utils import _generate_request_id, dict_to_proto_struct, fix_tuple_length +from pinecone.utils import fix_tuple_length from pinecone.utils.constants import ( - MAX_MSG_SIZE, - REQUEST_ID, - CLIENT_VERSION, REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS, ) -from pinecone.exceptions import PineconeException +from pinecone.data.grpc.base import GRPCIndexBase +from pinecone.data.grpc.future import PineconeGrpcFuture __all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] _logger = logging.getLogger(__name__) -class GRPCClientConfig(NamedTuple): - """ - GRPC client configuration options. - - :param secure: Whether to use encrypted protocol (SSL). defaults to True. - :type traceroute: bool, optional - :param timeout: defaults to 2 seconds. Fail if gateway doesn't receive response within timeout. - :type timeout: int, optional - :param conn_timeout: defaults to 1. Timeout to retry connection if gRPC is unavailable. 0 is no retry. - :type conn_timeout: int, optional - :param reuse_channel: Whether to reuse the same grpc channel for multiple requests - :type reuse_channel: bool, optional - :param retry_config: RetryConfig indicating how requests should be retried - :type retry_config: RetryConfig, optional - :param grpc_channel_options: A dict of gRPC channel arguments - :type grpc_channel_options: Dict[str, str] - """ - - secure: bool = True - timeout: int = 20 - conn_timeout: int = 1 - reuse_channel: bool = True - retry_config: Optional[RetryConfig] = None - grpc_channel_options: Dict[str, str] = None - - @classmethod - def _from_dict(cls, kwargs: dict): - cls_kwargs = {kk: vv for kk, vv in kwargs.items() if kk in cls._fields} - return cls(**cls_kwargs) - - -class GRPCIndexBase(ABC): - """ - Base class for grpc-based interaction with Pinecone indexes - """ - - _pool = None - - def __init__( - self, index_name: str, channel=None, grpc_config: GRPCClientConfig = None, _endpoint_override: str = None - ): - self.name = index_name - - self.grpc_client_config = grpc_config or GRPCClientConfig() - self.retry_config = self.grpc_client_config.retry_config or RetryConfig() - self.fixed_metadata = {"api-key": Config.API_KEY, "service-name": index_name, "client-version": CLIENT_VERSION} - self._endpoint_override = _endpoint_override - - self.method_config = json.dumps( - { - "methodConfig": [ - { - "name": [{"service": "VectorService.Upsert"}], - "retryPolicy": { - "maxAttempts": 5, - "initialBackoff": "0.1s", - "maxBackoff": "1s", - "backoffMultiplier": 2, - "retryableStatusCodes": ["UNAVAILABLE"], - }, - }, - { - "name": [{"service": "VectorService"}], - "retryPolicy": { - "maxAttempts": 5, - "initialBackoff": "0.1s", - "maxBackoff": "1s", - "backoffMultiplier": 2, - "retryableStatusCodes": ["UNAVAILABLE"], - }, - }, - ] - } - ) - - self._channel = channel or self._gen_channel() - self.stub = self.stub_class(self._channel) - - @property - @abstractmethod - def stub_class(self): - pass - - def _endpoint(self): - return ( - self._endpoint_override - if self._endpoint_override - else f"{self.name}-{Config.PROJECT_NAME}.svc.{Config.ENVIRONMENT}.pinecone.io:443" - ) - - def _gen_channel(self, options=None): - target = self._endpoint() - default_options = { - "grpc.max_send_message_length": MAX_MSG_SIZE, - "grpc.max_receive_message_length": MAX_MSG_SIZE, - "grpc.service_config": self.method_config, - "grpc.enable_retries": True, - } - if self.grpc_client_config.secure: - default_options["grpc.ssl_target_name_override"] = target.split(":")[0] - user_provided_options = options or {} - _options = tuple((k, v) for k, v in {**default_options, **user_provided_options}.items()) - _logger.debug( - "creating new channel with endpoint %s options %s and config %s", target, _options, self.grpc_client_config - ) - if not self.grpc_client_config.secure: - channel = grpc.insecure_channel(target, options=_options) - else: - root_cas = open(certifi.where(), "rb").read() - tls = grpc.ssl_channel_credentials(root_certificates=root_cas) - channel = grpc.secure_channel(target, tls, options=_options) - - return channel - - @property - def channel(self): - """Creates GRPC channel.""" - if self.grpc_client_config.reuse_channel and self._channel and self.grpc_server_on(): - return self._channel - self._channel = self._gen_channel() - return self._channel - - def grpc_server_on(self) -> bool: - try: - grpc.channel_ready_future(self._channel).result(timeout=self.grpc_client_config.conn_timeout) - return True - except grpc.FutureTimeoutError: - return False - - def close(self): - """Closes the connection to the index.""" - try: - self._channel.close() - except TypeError: - pass - - def _wrap_grpc_call( - self, func, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None - ): - @wraps(func) - def wrapped(): - user_provided_metadata = metadata or {} - _metadata = tuple( - (k, v) for k, v in {**self.fixed_metadata, **self._request_metadata(), **user_provided_metadata}.items() - ) - try: - return func( - request, - timeout=timeout, - metadata=_metadata, - credentials=credentials, - wait_for_ready=wait_for_ready, - compression=compression, - ) - except _InactiveRpcError as e: - raise PineconeException(e._state.debug_error_string) from e - - return wrapped() - - def _request_metadata(self) -> Dict[str, str]: - return {REQUEST_ID: _generate_request_id()} - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - -def parse_sparse_values(sparse_values: dict): - return ( - SparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) - if sparse_values - else SparseValues(indices=[], values=[]) - ) - - -def parse_fetch_response(response: dict): - vd = {} - vectors = response.get("vectors") - if not vectors: - return None - for id, vec in vectors.items(): - v_obj = _Vector( - id=vec["id"], - values=vec["values"], - sparse_values=parse_sparse_values(vec.get("sparseValues")), - metadata=vec.get("metadata", None), - _check_type=False, - ) - vd[id] = v_obj - namespace = response.get("namespace", "") - return FetchResponse(vectors=vd, namespace=namespace, _check_type=False) - - -def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): - res = [] - - # TODO: consider deleting this deprecated case - for match in response.get("results", []): - namespace = match.get("namespace", "") - m = [] - if "matches" in match: - for item in match["matches"]: - sc = ScoredVector( - id=item["id"], - score=item.get("score", 0.0), - values=item.get("values", []), - sparse_values=parse_sparse_values(item.get("sparseValues")), - metadata=item.get("metadata", {}), - ) - m.append(sc) - res.append(SingleQueryResults(matches=m, namespace=namespace)) - - m = [] - for item in response.get("matches", []): - sc = ScoredVector( - id=item["id"], - score=item.get("score", 0.0), - values=item.get("values", []), - sparse_values=parse_sparse_values(item.get("sparseValues")), - metadata=item.get("metadata", {}), - _check_type=_check_type, - ) - m.append(sc) - - kwargs = {"_check_type": _check_type} - if unary_query: - kwargs["namespace"] = response.get("namespace", "") - kwargs["matches"] = m - else: - kwargs["results"] = res - return QueryResponse(**kwargs) - - -def parse_stats_response(response: dict): - fullness = response.get("indexFullness", 0.0) - total_vector_count = response.get("totalVectorCount", 0) - dimension = response.get("dimension", 0) - summaries = response.get("namespaces", {}) - namespace_summaries = {} - for key in summaries: - vc = summaries[key].get("vectorCount", 0) - namespace_summaries[key] = NamespaceSummary(vector_count=vc) - return DescribeIndexStatsResponse( - namespaces=namespace_summaries, - dimension=dimension, - index_fullness=fullness, - total_vector_count=total_vector_count, - _check_type=False, - ) - - -class PineconeGrpcFuture: - def __init__(self, delegate): - self._delegate = delegate - - def cancel(self): - return self._delegate.cancel() - - def cancelled(self): - return self._delegate.cancelled() - - def running(self): - return self._delegate.running() - - def done(self): - return self._delegate.done() - - def add_done_callback(self, fun): - return self._delegate.add_done_callback(fun) - - def result(self, timeout=None): - try: - return self._delegate.result(timeout=timeout) - except _MultiThreadedRendezvous as e: - raise PineconeException(e._state.debug_error_string) from e - - def exception(self, timeout=None): - return self._delegate.exception(timeout=timeout) - - def traceback(self, timeout=None): - return self._delegate.traceback(timeout=timeout) - - class GRPCIndex(GRPCIndexBase): - """A client for interacting with a Pinecone index via GRPC API.""" @property @@ -840,4 +547,4 @@ def _parse_sparse_values_arg( f"Received: {sparse_values}" ) - return GRPCSparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) \ No newline at end of file + return GRPCSparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) diff --git a/pinecone/grpc/protos/vector_column_service_pb2.py b/pinecone/data/grpc/protos/vector_column_service_pb2.py similarity index 99% rename from pinecone/grpc/protos/vector_column_service_pb2.py rename to pinecone/data/grpc/protos/vector_column_service_pb2.py index cab350a61..1b4ebadc1 100644 --- a/pinecone/grpc/protos/vector_column_service_pb2.py +++ b/pinecone/data/grpc/protos/vector_column_service_pb2.py @@ -1290,4 +1290,4 @@ DESCRIPTOR.services_by_name["VectorColumnService"] = _VECTORCOLUMNSERVICE -# @@protoc_insertion_point(module_scope) \ No newline at end of file +# @@protoc_insertion_point(module_scope) diff --git a/pinecone/grpc/protos/vector_column_service_pb2.pyi b/pinecone/data/grpc/protos/vector_column_service_pb2.pyi similarity index 99% rename from pinecone/grpc/protos/vector_column_service_pb2.pyi rename to pinecone/data/grpc/protos/vector_column_service_pb2.pyi index 3b0176f67..3b85ddb13 100644 --- a/pinecone/grpc/protos/vector_column_service_pb2.pyi +++ b/pinecone/data/grpc/protos/vector_column_service_pb2.pyi @@ -347,4 +347,4 @@ class DescribeIndexStatsResponse(google___protobuf___message___Message): self, field_name: typing_extensions___Literal["dimension", b"dimension", "namespaces", b"namespaces"] ) -> None: ... -type___DescribeIndexStatsResponse = DescribeIndexStatsResponse \ No newline at end of file +type___DescribeIndexStatsResponse = DescribeIndexStatsResponse diff --git a/pinecone/grpc/protos/vector_column_service_pb2_grpc.py b/pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py similarity index 99% rename from pinecone/grpc/protos/vector_column_service_pb2_grpc.py rename to pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py index 93db50203..677e12b4b 100644 --- a/pinecone/grpc/protos/vector_column_service_pb2_grpc.py +++ b/pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py @@ -264,4 +264,4 @@ def DescribeIndexStats( wait_for_ready, timeout, metadata, - ) \ No newline at end of file + ) diff --git a/pinecone/grpc/retry.py b/pinecone/data/grpc/retry.py similarity index 99% rename from pinecone/grpc/retry.py rename to pinecone/data/grpc/retry.py index e1ec306a3..b27182884 100644 --- a/pinecone/grpc/retry.py +++ b/pinecone/data/grpc/retry.py @@ -84,4 +84,4 @@ class RetryConfig(NamedTuple): max_attempts: int = 4 sleep_policy: SleepPolicy = ExponentialBackoff(init_backoff_ms=100, max_backoff_ms=1600, multiplier=2) - retryable_status: Optional[Tuple[grpc.StatusCode, ...]] = (grpc.StatusCode.UNAVAILABLE,) \ No newline at end of file + retryable_status: Optional[Tuple[grpc.StatusCode, ...]] = (grpc.StatusCode.UNAVAILABLE,) diff --git a/pinecone/data/grpc/utils.py b/pinecone/data/grpc/utils.py new file mode 100644 index 000000000..fc69c83e5 --- /dev/null +++ b/pinecone/data/grpc/utils.py @@ -0,0 +1,107 @@ +import uuid + +from google.protobuf.struct_pb2 import Struct + +from pinecone.core.client.models import ( + Vector as _Vector, + ScoredVector, + SparseValues, + FetchResponse, + SingleQueryResults, + QueryResponse, + DescribeIndexStatsResponse, + NamespaceSummary, +) + +def _generate_request_id() -> str: + return str(uuid.uuid4()) + +def dict_to_proto_struct(d: dict) -> "Struct": + if not d: + d = {} + s = Struct() + s.update(d) + return s + +def parse_sparse_values(sparse_values: dict): + return ( + SparseValues(indices=sparse_values["indices"], values=sparse_values["values"]) + if sparse_values + else SparseValues(indices=[], values=[]) + ) + + +def parse_fetch_response(response: dict): + vd = {} + vectors = response.get("vectors") + if not vectors: + return None + for id, vec in vectors.items(): + v_obj = _Vector( + id=vec["id"], + values=vec["values"], + sparse_values=parse_sparse_values(vec.get("sparseValues")), + metadata=vec.get("metadata", None), + _check_type=False, + ) + vd[id] = v_obj + namespace = response.get("namespace", "") + return FetchResponse(vectors=vd, namespace=namespace, _check_type=False) + + +def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): + res = [] + + # TODO: consider deleting this deprecated case + for match in response.get("results", []): + namespace = match.get("namespace", "") + m = [] + if "matches" in match: + for item in match["matches"]: + sc = ScoredVector( + id=item["id"], + score=item.get("score", 0.0), + values=item.get("values", []), + sparse_values=parse_sparse_values(item.get("sparseValues")), + metadata=item.get("metadata", {}), + ) + m.append(sc) + res.append(SingleQueryResults(matches=m, namespace=namespace)) + + m = [] + for item in response.get("matches", []): + sc = ScoredVector( + id=item["id"], + score=item.get("score", 0.0), + values=item.get("values", []), + sparse_values=parse_sparse_values(item.get("sparseValues")), + metadata=item.get("metadata", {}), + _check_type=_check_type, + ) + m.append(sc) + + kwargs = {"_check_type": _check_type} + if unary_query: + kwargs["namespace"] = response.get("namespace", "") + kwargs["matches"] = m + else: + kwargs["results"] = res + return QueryResponse(**kwargs) + + +def parse_stats_response(response: dict): + fullness = response.get("indexFullness", 0.0) + total_vector_count = response.get("totalVectorCount", 0) + dimension = response.get("dimension", 0) + summaries = response.get("namespaces", {}) + namespace_summaries = {} + for key in summaries: + vc = summaries[key].get("vectorCount", 0) + namespace_summaries[key] = NamespaceSummary(vector_count=vc) + return DescribeIndexStatsResponse( + namespaces=namespace_summaries, + dimension=dimension, + index_fullness=fullness, + total_vector_count=total_vector_count, + _check_type=False, + ) diff --git a/pinecone/index.py b/pinecone/data/index.py similarity index 95% rename from pinecone/index.py rename to pinecone/data/index.py index 663645d6f..c2250352c 100644 --- a/pinecone/index.py +++ b/pinecone/data/index.py @@ -1,3 +1,5 @@ +import os + from tqdm.autonotebook import tqdm from importlib.util import find_spec import numbers @@ -6,12 +8,12 @@ from collections.abc import Iterable, Mapping from typing import Union, List, Tuple, Optional, Dict, Any -from .core.client.models.sparse_values import SparseValues -from pinecone import Config +from pinecone.config import Config + +from pinecone.core.client.models.sparse_values import SparseValues from pinecone.core.client import ApiClient -from .core.client.models import ( +from pinecone.core.client.models import ( FetchResponse, - ProtobufAny, QueryRequest, QueryResponse, QueryVector, @@ -28,13 +30,12 @@ DescribeIndexStatsRequest, ) from pinecone.core.client.api.vector_operations_api import VectorOperationsApi -from .utils import fix_tuple_length, get_user_agent, warn_deprecated +from ..utils import fix_tuple_length, get_user_agent, warn_deprecated import copy __all__ = [ "Index", "FetchResponse", - "ProtobufAny", "QueryRequest", "QueryResponse", "QueryVector", @@ -52,8 +53,8 @@ "SparseValues", ] -from .utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS -from .utils.error_handling import validate_and_convert_errors +from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS +from ..utils.error_handling import validate_and_convert_errors _OPENAPI_ENDPOINT_PARAMS = ( "_return_http_data_only", @@ -81,25 +82,30 @@ def upsert_numpy_deprecation_notice(context): warn_deprecated(message, deprecated_in="2.2.1", removal_in="3.0.0") -class Index(ApiClient): +class Index(): """ A client for interacting with a Pinecone index via REST API. For improved performance, use the Pinecone GRPC index client. """ - def __init__(self, index_name: str, pool_threads=1): - openapi_client_config = copy.deepcopy(Config.OPENAPI_CONFIG) - openapi_client_config.api_key = openapi_client_config.api_key or {} - openapi_client_config.api_key["ApiKeyAuth"] = openapi_client_config.api_key.get("ApiKeyAuth", Config.API_KEY) - openapi_client_config.server_variables = openapi_client_config.server_variables or {} - openapi_client_config.server_variables = { - **{"environment": Config.ENVIRONMENT, "index_name": index_name, "project_name": Config.PROJECT_NAME}, - **openapi_client_config.server_variables, - } - super().__init__(configuration=openapi_client_config, pool_threads=pool_threads) - self.user_agent = get_user_agent() - self._vector_api = VectorOperationsApi(self) + def __init__(self, api_key: str, host: str, pool_threads=1, **kwargs): + api_key = api_key or kwargs.get("api_key") + host = host or kwargs.get('host') + pool_threads = pool_threads or kwargs.get("pool_threads") + + self._config = Config(api_key=api_key, host=host, **kwargs) + + api_client = ApiClient(configuration=self._config.OPENAPI_CONFIG, pool_threads=pool_threads) + api_client.user_agent = get_user_agent() + self._api_client = api_client + self._vector_api = VectorOperationsApi(api_client=api_client) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._api_client.close() @validate_and_convert_errors def upsert( diff --git a/pinecone/deprecated/__init__.py b/pinecone/deprecated/__init__.py new file mode 100644 index 000000000..f67d72268 --- /dev/null +++ b/pinecone/deprecated/__init__.py @@ -0,0 +1 @@ +from .legacy_utils import * \ No newline at end of file diff --git a/pinecone/deprecated/legacy_utils.py b/pinecone/deprecated/legacy_utils.py new file mode 100644 index 000000000..19b5f58ec --- /dev/null +++ b/pinecone/deprecated/legacy_utils.py @@ -0,0 +1,88 @@ +import re +import uuid +from typing import List + +from pinecone.utils import warn_deprecated + +try: + from pinecone.data.grpc.protos import vector_column_service_pb2 + from google.protobuf.struct_pb2 import Struct + from google.protobuf import json_format + import numpy as np + import lz4.frame +except Exception: + pass # ignore for non-[grpc] installations + +DNS_COMPATIBLE_REGEX = re.compile("^[a-z0-9]([a-z0-9]|[-])+[a-z0-9]$") + + +def dump_numpy_public(np_array: "np.ndarray", compressed: bool = False) -> "vector_column_service_pb2.NdArray": + """ + Dump numpy array to vector_column_service_pb2.NdArray + """ + warn_deprecated( + "dump_numpy_public and all numpy-related features will be removed in a future version", + deprecated_in="2.2.1", + removal_in="3.0.0", + ) + protobuf_arr = vector_column_service_pb2.NdArray() + protobuf_arr.dtype = str(np_array.dtype) + protobuf_arr.shape.extend(np_array.shape) + if compressed: + protobuf_arr.buffer = lz4.frame.compress(np_array.tobytes()) + protobuf_arr.compressed = True + else: + protobuf_arr.buffer = np_array.tobytes() + return protobuf_arr + + +def dump_strings_public(strs: List[str], compressed: bool = False) -> "vector_column_service_pb2.NdArray": + warn_deprecated( + "dump_strings_public and all numpy-related features will be removed in a future version", + deprecated_in="2.2.1", + removal_in="3.0.0", + ) + return dump_numpy_public(np.array(strs, dtype="S"), compressed=compressed) + + + +def validate_dns_name(name): + if not DNS_COMPATIBLE_REGEX.match(name): + raise ValueError( + "{} is invalid - service names and node names must consist of lower case " + "alphanumeric characters or '-', start with an alphabetic character, and end with an " + "alphanumeric character (e.g. 'my-name', or 'abc-123')".format(name) + ) + + +def proto_struct_to_dict(s: "Struct") -> dict: + return json_format.MessageToDict(s) + + +def load_numpy_public(proto_arr: "vector_column_service_pb2.NdArray") -> "np.ndarray": + """ + Load numpy array from protobuf + :param proto_arr: + :return: + """ + warn_deprecated( + "load_numpy_public and all numpy-related features will be removed in a future version", + deprecated_in="2.2.1", + removal_in="3.0.0", + ) + if len(proto_arr.shape) == 0: + return np.array([]) + if proto_arr.compressed: + numpy_arr = np.frombuffer(lz4.frame.decompress(proto_arr.buffer), dtype=proto_arr.dtype) + else: + numpy_arr = np.frombuffer(proto_arr.buffer, dtype=proto_arr.dtype) + return numpy_arr.reshape(proto_arr.shape) + + +def load_strings_public(proto_arr: "vector_column_service_pb2.NdArray") -> List[str]: + warn_deprecated( + "load_strings_public and all numpy-related features will be removed in a future version", + deprecated_in="2.2.1", + removal_in="3.0.0", + ) + return [str(item, "utf-8") for item in load_numpy_public(proto_arr)] diff --git a/pinecone/exceptions.py b/pinecone/exceptions.py index 62da708f7..98610be39 100644 --- a/pinecone/exceptions.py +++ b/pinecone/exceptions.py @@ -17,7 +17,11 @@ class PineconeException(Exception): class PineconeProtocolError(PineconeException): """Raised when something unexpected happens mid-request/response.""" +class PineconeConfigurationError(PineconeException): + """Raised when a configuration error occurs.""" + __all__ = [ + "PineconeConfigurationError", "PineconeException", "PineconeProtocolError", "OpenApiException", diff --git a/pinecone/manage.py b/pinecone/manage.py deleted file mode 100644 index 5f3227a8f..000000000 --- a/pinecone/manage.py +++ /dev/null @@ -1,300 +0,0 @@ -import time -from typing import NamedTuple, Optional - -import pinecone -from pinecone.config import Config -from pinecone.core.client.api.index_operations_api import IndexOperationsApi -from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.models.create_request import CreateRequest -from pinecone.core.client.models.patch_request import PatchRequest -from pinecone.core.client.models.create_collection_request import CreateCollectionRequest -from pinecone.utils import get_user_agent - -__all__ = [ - "create_index", - "delete_index", - "describe_index", - "list_indexes", - "scale_index", - "create_collection", - "describe_collection", - "list_collections", - "delete_collection", - "configure_index", - "CollectionDescription", - "IndexDescription", -] - - -class IndexDescription(NamedTuple): - name: str - metric: str - replicas: int - dimension: int - shards: int - pods: int - pod_type: str - status: None - metadata_config: None - source_collection: None - - -class CollectionDescription(object): - def __init__(self, keys, values): - for k, v in zip(keys, values): - self.__dict__[k] = v - - def __str__(self): - return str(self.__dict__) - - -def _get_api_instance(): - client_config = Config.OPENAPI_CONFIG - client_config.api_key = client_config.api_key or {} - client_config.api_key["ApiKeyAuth"] = client_config.api_key.get("ApiKeyAuth", Config.API_KEY) - client_config.server_variables = {**{"environment": Config.ENVIRONMENT}, **client_config.server_variables} - - # If a custom host has been passed with initialization pass it to the client_config - if (Config.CONTROLLER_HOST): - client_config.host = Config.CONTROLLER_HOST - - api_client = ApiClient(configuration=client_config) - api_client.user_agent = get_user_agent() - api_instance = IndexOperationsApi(api_client) - return api_instance - - -def _get_status(name: str): - api_instance = _get_api_instance() - response = api_instance.describe_index(name) - return response["status"] - - -def create_index( - name: str, - dimension: int, - cloud: str, - region: str, - capacity_mode: str, - timeout: int = None, - index_type: str = "approximated", - metric: str = "cosine", - replicas: int = 1, - shards: int = 1, - pods: int = 1, - pod_type: str = "p1", - index_config: dict = None, - metadata_config: dict = None, - source_collection: str = "", -): - """Creates a Pinecone index. - - :param name: the name of the index. - :type name: str - :param dimension: the dimension of vectors that would be inserted in the index - :param cloud: The cloud where you would like your index hosted. One of `{"aws", "gcp"}`. - :param region: The region where you would like your index hosted. - :param capacity_mode: The capacity mode for the index. One of `{"pod"}`. - :param index_type: type of index, one of `{"approximated", "exact"}`, defaults to "approximated". - The "approximated" index uses fast approximate search algorithms developed by Pinecone. - The "exact" index uses accurate exact search algorithms. - It performs exhaustive searches and thus it is usually slower than the "approximated" index. - :type index_type: str, optional - :param metric: type of metric used in the vector index, one of `{"cosine", "dotproduct", "euclidean"}`, defaults to "cosine". - Use "cosine" for cosine similarity, - "dotproduct" for dot-product, - and "euclidean" for euclidean distance. - :type metric: str, optional - :param replicas: the number of replicas, defaults to 1. - Use at least 2 replicas if you need high availability (99.99% uptime) for querying. - For additional throughput (QPS) your index needs to support, provision additional replicas. - :type replicas: int, optional - :param shards: the number of shards per index, defaults to 1. - Use 1 shard per 1GB of vectors - :type shards: int,optional - :param pods: Total number of pods to be used by the index. pods = shard*replicas - :type pods: int,optional - :param pod_type: the pod type to be used for the index. can be one of p1 or s1. - :type pod_type: str,optional - :param index_config: Advanced configuration options for the index - :param metadata_config: Configuration related to the metadata index - :type metadata_config: dict, optional - :param source_collection: Collection name to create the index from - :type metadata_config: str, optional - :type timeout: int, optional - :param timeout: Timeout for 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 - """ - api_instance = _get_api_instance() - - api_instance.create_index( - create_request=CreateRequest( - name=name, - dimension=dimension, - cloud=cloud, - region=region, - capacity_mode=capacity_mode, - index_type=index_type, - metric=metric, - replicas=replicas, - shards=shards, - pods=pods, - pod_type=pod_type, - index_config=index_config or {}, - metadata_config=metadata_config, - source_collection=source_collection, - ) - ) - - def is_ready(): - status = _get_status(name) - ready = status["ready"] - return ready - - if timeout == -1: - return - if timeout is None: - while not is_ready(): - time.sleep(5) - else: - while (not is_ready()) and timeout >= 0: - time.sleep(5) - timeout -= 5 - if timeout and timeout < 0: - raise ( - TimeoutError( - "Please call the describe_index API ({}) to confirm index status.".format( - "https://www.pinecone.io/docs/api/operation/describe_index/" - ) - ) - ) - - -def delete_index(name: str, timeout: int = None): - """Deletes a Pinecone index. - - :param name: the name of the index. - :type name: str - :param timeout: Timeout for 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 - :type timeout: int, optional - """ - api_instance = _get_api_instance() - api_instance.delete_index(name) - - def get_remaining(): - return name in api_instance.list_indexes() - - if timeout == -1: - return - - if timeout is None: - while get_remaining(): - time.sleep(5) - else: - while get_remaining() and timeout >= 0: - time.sleep(5) - timeout -= 5 - if timeout and timeout < 0: - raise ( - TimeoutError( - "Please call the list_indexes API ({}) to confirm if index is deleted".format( - "https://www.pinecone.io/docs/api/operation/list_indexes/" - ) - ) - ) - - -def list_indexes(): - """Lists all indexes.""" - api_instance = _get_api_instance() - response = api_instance.list_indexes() - return response - - -def describe_index(name: str): - """Describes a Pinecone index. - - :param name: the name of the index to describe. - :return: Returns an `IndexDescription` object - """ - api_instance = _get_api_instance() - response = api_instance.describe_index(name) - db = response["database"] - ready = response["status"]["ready"] - state = response["status"]["state"] - return IndexDescription( - name=db["name"], - metric=db["metric"], - replicas=db["replicas"], - dimension=db["dimension"], - shards=db["shards"], - pods=db.get("pods", db["shards"] * db["replicas"]), - pod_type=db.get("pod_type", "p1"), - status={"ready": ready, "state": state}, - metadata_config=db.get("metadata_config"), - source_collection=db.get("source_collection", ""), - ) - - -def scale_index(name: str, replicas: int): - """Increases number of replicas for the index. - - :param name: the name of the Index - :type name: str - :param replicas: the number of replicas in the index now, lowest value is 0. - :type replicas: int - """ - api_instance = _get_api_instance() - api_instance.configure_index(name, patch_request=PatchRequest(replicas=replicas, pod_type="")) - - -def create_collection(name: str, source: str): - """Create a collection - :param name: Name of the collection - :param source: Name of the source index - """ - api_instance = _get_api_instance() - api_instance.create_collection(create_collection_request=CreateCollectionRequest(name=name, source=source)) - - -def list_collections(): - """List all collections""" - api_instance = _get_api_instance() - response = api_instance.list_collections() - return response - - -def delete_collection(name: str): - """Deletes a collection. - :param: name: The name of the collection - """ - api_instance = _get_api_instance() - api_instance.delete_collection(name) - - -def describe_collection(name: str): - """Describes a collection. - :param: The name of the collection - :return: Description of the collection - """ - api_instance = _get_api_instance() - response = api_instance.describe_collection(name).to_dict() - response_object = CollectionDescription(response.keys(), response.values()) - return response_object - - -def configure_index(name: str, replicas: Optional[int] = None, pod_type: Optional[str] = ""): - """Changes current configuration of the 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. - """ - api_instance = _get_api_instance() - config_args = {} - if pod_type != "": - config_args.update(pod_type=pod_type) - if replicas: - config_args.update(replicas=replicas) - patch_request = PatchRequest(**config_args) - api_instance.configure_index(name, patch_request=patch_request) diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py index 08f885ebf..c826e0ff7 100644 --- a/pinecone/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -1,136 +1,5 @@ -import inspect -import logging -import re -import uuid -import warnings -from pathlib import Path -from typing import List - -import requests -import urllib3 - -try: - from pinecone.grpc.protos import vector_column_service_pb2 - from google.protobuf.struct_pb2 import Struct - from google.protobuf import json_format - import numpy as np - import lz4.frame -except Exception: - pass # ignore for non-[grpc] installations - -DNS_COMPATIBLE_REGEX = re.compile("^[a-z0-9]([a-z0-9]|[-])+[a-z0-9]$") - - -def dump_numpy_public(np_array: "np.ndarray", compressed: bool = False) -> "vector_column_service_pb2.NdArray": - """ - Dump numpy array to vector_column_service_pb2.NdArray - """ - warn_deprecated( - "dump_numpy_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - protobuf_arr = vector_column_service_pb2.NdArray() - protobuf_arr.dtype = str(np_array.dtype) - protobuf_arr.shape.extend(np_array.shape) - if compressed: - protobuf_arr.buffer = lz4.frame.compress(np_array.tobytes()) - protobuf_arr.compressed = True - else: - protobuf_arr.buffer = np_array.tobytes() - return protobuf_arr - - -def dump_strings_public(strs: List[str], compressed: bool = False) -> "vector_column_service_pb2.NdArray": - warn_deprecated( - "dump_strings_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - return dump_numpy_public(np.array(strs, dtype="S"), compressed=compressed) - - -def get_version(): - return Path(__file__).parent.parent.joinpath("__version__").read_text().strip() - - -def get_environment(): - return Path(__file__).parent.parent.joinpath("__environment__").read_text().strip() - - -def validate_dns_name(name): - if not DNS_COMPATIBLE_REGEX.match(name): - raise ValueError( - "{} is invalid - service names and node names must consist of lower case " - "alphanumeric characters or '-', start with an alphabetic character, and end with an " - "alphanumeric character (e.g. 'my-name', or 'abc-123')".format(name) - ) - - -def _generate_request_id() -> str: - return str(uuid.uuid4()) - - -def fix_tuple_length(t, n): - """Extend tuple t to length n by adding None items at the end of the tuple. Return the new tuple.""" - return t + ((None,) * (n - len(t))) if len(t) < n else t - - -def get_user_agent(): - client_id = f"python-client-{get_version()}" - user_agent_details = {"requests": requests.__version__, "urllib3": urllib3.__version__} - user_agent = "{} ({})".format(client_id, ", ".join([f"{k}:{v}" for k, v in user_agent_details.items()])) - return user_agent - - -def dict_to_proto_struct(d: dict) -> "Struct": - if not d: - d = {} - s = Struct() - s.update(d) - return s - - -def proto_struct_to_dict(s: "Struct") -> dict: - return json_format.MessageToDict(s) - - -def load_numpy_public(proto_arr: "vector_column_service_pb2.NdArray") -> "np.ndarray": - """ - Load numpy array from protobuf - :param proto_arr: - :return: - """ - warn_deprecated( - "load_numpy_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - if len(proto_arr.shape) == 0: - return np.array([]) - if proto_arr.compressed: - numpy_arr = np.frombuffer(lz4.frame.decompress(proto_arr.buffer), dtype=proto_arr.dtype) - else: - numpy_arr = np.frombuffer(proto_arr.buffer, dtype=proto_arr.dtype) - return numpy_arr.reshape(proto_arr.shape) - - -def load_strings_public(proto_arr: "vector_column_service_pb2.NdArray") -> List[str]: - warn_deprecated( - "load_strings_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - return [str(item, "utf-8") for item in load_numpy_public(proto_arr)] - - -def warn_deprecated(description: str = "", deprecated_in: str = None, removal_in: str = None): - message = f"DEPRECATED since v{deprecated_in} [Will be removed in v{removal_in}]: {description}" - warnings.warn(message, FutureWarning) - - -def check_kwargs(caller, given): - argspec = inspect.getfullargspec(caller) - diff = set(given).difference(argspec.args) - if diff: - logging.exception(caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), exc_info=False) \ No newline at end of file +from .check_kwargs import check_kwargs +from .environment import get_version, get_environment +from .user_agent import get_user_agent +from .deprecation_notice import warn_deprecated +from .fix_tuple_length import fix_tuple_length \ No newline at end of file diff --git a/pinecone/utils/check_kwargs.py b/pinecone/utils/check_kwargs.py new file mode 100644 index 000000000..f03bc7b71 --- /dev/null +++ b/pinecone/utils/check_kwargs.py @@ -0,0 +1,8 @@ +import inspect +import logging + +def check_kwargs(caller, given): + argspec = inspect.getfullargspec(caller) + diff = set(given).difference(argspec.args) + if diff: + logging.exception(caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), exc_info=False) diff --git a/pinecone/utils/constants.py b/pinecone/utils/constants.py index c415a36a6..4b3090a76 100644 --- a/pinecone/utils/constants.py +++ b/pinecone/utils/constants.py @@ -1,10 +1,7 @@ import os import enum -from pinecone.utils import get_environment, get_version - -PARENT_LOGGER_NAME = "pinecone" -DEFAULT_PARENT_LOGGER_LEVEL = "ERROR" +from .environment import get_environment, get_version MAX_MSG_SIZE = 128 * 1024 * 1024 @@ -30,9 +27,5 @@ class NodeType(str, enum.Enum): CLIENT_VERSION = get_version() CLIENT_ID = f"python-client-{CLIENT_VERSION}" -TCP_KEEPINTVL = 60 # Sec -TCP_KEEPIDLE = 300 # Sec -TCP_KEEPCNT = 4 - REQUIRED_VECTOR_FIELDS = {"id", "values"} -OPTIONAL_VECTOR_FIELDS = {"sparse_values", "metadata"} \ No newline at end of file +OPTIONAL_VECTOR_FIELDS = {"sparse_values", "metadata"} diff --git a/pinecone/utils/deprecation_notice.py b/pinecone/utils/deprecation_notice.py new file mode 100644 index 000000000..a27fe9c57 --- /dev/null +++ b/pinecone/utils/deprecation_notice.py @@ -0,0 +1,5 @@ +import warnings + +def warn_deprecated(description: str = "", deprecated_in: str = None, removal_in: str = None): + message = f"DEPRECATED since v{deprecated_in} [Will be removed in v{removal_in}]: {description}" + warnings.warn(message, FutureWarning) \ No newline at end of file diff --git a/pinecone/utils/environment.py b/pinecone/utils/environment.py new file mode 100644 index 000000000..d80e868ed --- /dev/null +++ b/pinecone/utils/environment.py @@ -0,0 +1,8 @@ +from pathlib import Path + +def get_version(): + return Path(__file__).parent.parent.joinpath("__version__").read_text().strip() + + +def get_environment(): + return Path(__file__).parent.parent.joinpath("__environment__").read_text().strip() \ No newline at end of file diff --git a/pinecone/utils/error_handling.py b/pinecone/utils/error_handling.py index f64b1a59d..733e6091f 100644 --- a/pinecone/utils/error_handling.py +++ b/pinecone/utils/error_handling.py @@ -3,19 +3,14 @@ from urllib3.exceptions import MaxRetryError, ProtocolError -from pinecone import Config - def validate_and_convert_errors(func): @wraps(func) def inner_func(*args, **kwargs): - Config.validate() # raises exceptions in case of invalid config try: return func(*args, **kwargs) except MaxRetryError as e: if isinstance(e.reason, ProtocolError): - raise ProtocolError( - f"Failed to connect to {e.url}; did you specify the correct index name?" - ) from e + raise ProtocolError(f"Failed to connect to {e.url}; did you specify the correct index name?") from e else: raise except ProtocolError as e: @@ -24,4 +19,4 @@ def inner_func(*args, **kwargs): # Override signature sig = inspect.signature(func) inner_func.__signature__ = sig - return inner_func \ No newline at end of file + return inner_func diff --git a/pinecone/utils/fix_tuple_length.py b/pinecone/utils/fix_tuple_length.py new file mode 100644 index 000000000..fa4fc5eb6 --- /dev/null +++ b/pinecone/utils/fix_tuple_length.py @@ -0,0 +1,3 @@ +def fix_tuple_length(t, n): + """Extend tuple t to length n by adding None items at the end of the tuple. Return the new tuple.""" + return t + ((None,) * (n - len(t))) if len(t) < n else t \ No newline at end of file diff --git a/pinecone/utils/user_agent.py b/pinecone/utils/user_agent.py new file mode 100644 index 000000000..439a7f5d9 --- /dev/null +++ b/pinecone/utils/user_agent.py @@ -0,0 +1,10 @@ +import requests +import urllib3 + +from pinecone.utils import get_version + +def get_user_agent(): + client_id = f"python-client-{get_version()}" + user_agent_details = {"requests": requests.__version__, "urllib3": urllib3.__version__} + user_agent = "{} ({})".format(client_id, ", ".join([f"{k}:{v}" for k, v in user_agent_details.items()])) + return user_agent \ No newline at end of file diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 7fec4826b..bc65abe0d 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,209 +1,80 @@ import pinecone -from pinecone.config import Config +from pinecone.exceptions import ApiKeyError, PineconeConfigurationError +from pinecone.config import PineconeConfig from pinecone.core.client.configuration import Configuration as OpenApiConfiguration import pytest -import tempfile import os +class TestConfig: + @pytest.fixture(autouse=True) + def run_before_and_after_tests(tmpdir): + """Fixture to execute asserts before and after a test is run""" -@pytest.fixture(autouse=True) -def run_before_and_after_tests(tmpdir): - """Fixture to execute asserts before and after a test is run""" + # Defend against unexpected env vars. Since we clear these variables below + # after each test execution, these should only be raised if there is + # test pollution in the environment coming from some other test file/setup. + known_env_vars = ["PINECONE_API_KEY", "PINECONE_ENVIRONMENT", "PINECONE_CONTROLLER_HOST"] + for var in known_env_vars: + if os.getenv(var): + raise ValueError(f"Unexpected env var {var} found in environment. Check for test pollution.") - # Defend against unexpected env vars. Since we clear these variables below - # after each test execution, these should only be raised if there is - # test pollution in the environment coming from some other test file/setup. - known_env_vars = ["PINECONE_API_KEY", "PINECONE_ENVIRONMENT", "PINECONE_CONTROLLER_HOST"] - for var in known_env_vars: - if os.getenv(var): - raise ValueError(f"Unexpected env var {var} found in environment. Check for test pollution.") + yield # this is where the testing happens - # Unfortunately since config is a singleton, we need to reset it manually between tests - pinecone.init() + # Teardown : Unset any env vars created during test execution + for var in known_env_vars: + if os.getenv(var): + del os.environ[var] - yield # this is where the testing happens + def test_init_with_environment_vars(self): + os.environ["PINECONE_API_KEY"] = "test-api-key" + os.environ["PINECONE_CONTROLLER_HOST"] = "test-controller-host" - # Teardown : Unset any env vars created during test execution - for var in known_env_vars: - if os.getenv(var): - del os.environ[var] + config = PineconeConfig() + assert config.API_KEY == "test-api-key" + assert config.HOST == "test-controller-host" -def test_default_config(): - """ - Test that default config is loaded when no config is specified. This not really a valid config that can be used, - but adding this test just to document the legacy behavior. - """ - pinecone.init() - assert Config.API_KEY == "" - assert Config.ENVIRONMENT == "us-west1-gcp" - assert Config.CONTROLLER_HOST == "https://controller.us-west1-gcp.pinecone.io" - assert Config.LOG_LEVEL == "ERROR" + def test_init_with_positional_args(self): + api_key = "my-api-key" + host = "my-controller-host" + config = PineconeConfig(api_key, host) -def test_init_with_environment_vars(): - os.environ["PINECONE_ENVIRONMENT"] = "test-env" - os.environ["PINECONE_API_KEY"] = "test-api-key" - os.environ["PINECONE_CONTROLLER_HOST"] = "test-controller-host" + assert config.API_KEY == api_key + assert config.HOST == host - pinecone.init() + def test_init_with_kwargs(self): + api_key = "my-api-key" + controller_host = "my-controller-host" + openapi_config = OpenApiConfiguration(api_key="openapi-api-key") - assert Config.API_KEY == "test-api-key" - assert Config.ENVIRONMENT == "test-env" - assert Config.CONTROLLER_HOST == "test-controller-host" + config = PineconeConfig(api_key=api_key, host=controller_host, openapi_config=openapi_config) + assert config.API_KEY == api_key + assert config.HOST == controller_host + assert config.OPENAPI_CONFIG == openapi_config -def test_init_with_positional_args(): - api_key = "my-api-key" - environment = "test-env" - host = "my-controller-host" - log_level = None # deprecated property but still in positional list - openapi_config = OpenApiConfiguration(api_key="openapi-api-key") + def test_init_with_mispelled_kwargs(self, caplog): + PineconeConfig(api_key='my-api-key', unknown_kwarg='bogus') + assert "__init__ had unexpected keyword argument(s): unknown_kwarg" in caplog.text - pinecone.init(api_key, host, environment, log_level, openapi_config) - - assert Config.API_KEY == api_key - assert Config.ENVIRONMENT == environment - assert Config.CONTROLLER_HOST == host - assert Config.OPENAPI_CONFIG == openapi_config - - -def test_init_with_kwargs(): - env = "test-env" - api_key = "my-api-key" - controller_host = "my-controller-host" - openapi_config = OpenApiConfiguration(api_key="openapi-api-key") - - pinecone.init(api_key=api_key, environment=env, host=controller_host, openapi_config=openapi_config) - - assert Config.API_KEY == api_key - assert Config.ENVIRONMENT == env - assert Config.CONTROLLER_HOST == controller_host - assert Config.OPENAPI_CONFIG == openapi_config - - -def test_init_with_mispelled_kwargs(caplog): - pinecone.init(invalid_kwarg="value") - assert "init had unexpected keyword argument(s): invalid_kwarg" in caplog.text - - -def test_init_with_file_based_configuration(): - """Test that config can be loaded from a file""" - env = "ini-test-env" - api_key = "ini-api-key" - controller_host = "ini-controller-host" - - with tempfile.NamedTemporaryFile(mode="w") as f: - f.write( - f""" - [default] - environment: {env} - api_key: {api_key} - controller_host: {controller_host} + def test_resolution_order_kwargs_over_env_vars(self): """ - ) - f.flush() - - pinecone.init(config=f.name) - - assert Config.API_KEY == api_key - assert Config.ENVIRONMENT == env - assert Config.CONTROLLER_HOST == controller_host - - -def test_resolution_order_kwargs_over_env_vars(): - """ - Test that when config is present from multiple sources, - the order of precedence is kwargs > env vars - """ - os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" - os.environ["PINECONE_API_KEY"] = "env-var-api-key" - os.environ["PINECONE_CONTROLLER_HOST"] = "env-var-controller-host" - - env = "kwargs-env" - api_key = "kwargs-api-key" - controller_host = "kwargs-controller-host" - - pinecone.init(environment=env, api_key=api_key, host=controller_host) - - assert Config.API_KEY == api_key - assert Config.ENVIRONMENT == env - assert Config.CONTROLLER_HOST == controller_host - - -def test_resolution_order_kwargs_over_config_file(): - """ - Test that when config is present from multiple sources, the order of - precedence is kwargs > config file - """ - env = "ini-test-env" - api_key = "ini-api-key" - controller_host = "ini-controller-host" - - kwargs_api_key = "kwargs-api-key" - - with tempfile.NamedTemporaryFile(mode="w") as f: - f.write( - f""" - [default] - environment: {env} - api_key: {api_key} - controller_host: {controller_host} + Test that when config is present from multiple sources, + the order of precedence is kwargs > env vars """ - ) - f.flush() - - pinecone.init(api_key=kwargs_api_key, config=f.name) - - # Properties passed as kwargs take precedence over config file - assert Config.API_KEY == kwargs_api_key - - # Properties not passed as kwargs loaded from config file - assert Config.ENVIRONMENT == env - assert Config.CONTROLLER_HOST == controller_host - - -def test_resolution_order_env_vars_over_config_file(): - """ - Test that when config is present from multiple sources, the order of precedence is - env vars > config file - """ - - os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" - os.environ["PINECONE_API_KEY"] = "env-var-api-key" - os.environ["PINECONE_CONTROLLER_HOST"] = "env-var-controller-host" - - with tempfile.NamedTemporaryFile(mode="w") as f: - f.write( - f""" - [default] - environment: ini-test-env - api_key: ini-api-key - controller_host: ini-controller-host - """ - ) - f.flush() - - pinecone.init(config=f.name) - - assert Config.API_KEY == "env-var-api-key" - assert Config.ENVIRONMENT == "env-var-env" - assert Config.CONTROLLER_HOST == "env-var-controller-host" - + os.environ["PINECONE_API_KEY"] = "env-var-api-key" + os.environ["PINECONE_CONTROLLER_HOST"] = "env-var-controller-host" -def test_init_from_mixed_sources(): - """ - Test that even when some vars are found in a higher precedence source, the rest - are still loaded from lower precedence sources - """ + api_key = "kwargs-api-key" + controller_host = "kwargs-controller-host" - os.environ["PINECONE_ENVIRONMENT"] = "env-var-env" - os.environ["PINECONE_API_KEY"] = "env-var-api-key" - controller_host = "kwargs-controller-host" + config = PineconeConfig(api_key=api_key, host=controller_host) - pinecone.init(host=controller_host) + assert config.API_KEY == api_key + assert config.HOST == controller_host - assert Config.API_KEY == "env-var-api-key" - assert Config.ENVIRONMENT == "env-var-env" - assert Config.CONTROLLER_HOST == controller_host + def test_errors_when_no_api_key_is_present(self): + with pytest.raises(PineconeConfigurationError): + PineconeConfig() \ No newline at end of file diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py new file mode 100644 index 000000000..b15c5acd1 --- /dev/null +++ b/tests/unit/test_control.py @@ -0,0 +1,66 @@ +import pytest +from pinecone import Pinecone +from pinecone.core.client.api import IndexOperationsApi +import time + +class TestControl: + def test_default_host(self): + p = Pinecone(api_key="123-456-789") + assert p.index_api.api_client.configuration.host == "https://api.pinecone.io" + + def test_passing_host(self): + p = Pinecone(api_key="123-456-789", host="my-host") + assert p.index_api.api_client.configuration.host == "my-host" + + + @pytest.mark.parametrize("timeout_value, describe_index_responses, expected_describe_index_calls, expected_sleep_calls", [ + # When timeout=None, describe_index is called until ready + (None, [{ "status": {"ready": False}}, {"status": {"ready": True}}], 2, 1), + + # Timeout of 10 seconds, describe_index called 3 times, sleep twice + (10, [{"status": {"ready": False}}, {"status": {"ready": False}}, {"status": {"ready": True}}], 3, 2), + + # When timeout=-1, create_index returns immediately without calling describe_index or sleep + (-1, [{"status": {"ready": False}}], 0, 0), + ]) + def test_create_index_with_timeout(self, mocker, timeout_value, describe_index_responses, expected_describe_index_calls, expected_sleep_calls): + mocker.patch.object(IndexOperationsApi, 'describe_index', side_effect=describe_index_responses) + mocker.patch.object(IndexOperationsApi, 'create_index') + mocker.patch('time.sleep') + + p = Pinecone(api_key="123-456-789") + p.create_index("my-index", 10, timeout=timeout_value, cloud="aws", region="us-west1", capacity_mode="pod") + + assert IndexOperationsApi.create_index.call_count == 1 + assert IndexOperationsApi.describe_index.call_count == expected_describe_index_calls + assert time.sleep.call_count == expected_sleep_calls + + def test_create_index_when_timeout_exceeded(self, mocker): + with pytest.raises(TimeoutError): + get_status_responses = [{"status": {"ready": False}}] * 5 + mocker.patch.object(IndexOperationsApi, 'describe_index', side_effect=get_status_responses) + mocker.patch.object(IndexOperationsApi, 'create_index') + mocker.patch('time.sleep') + + p = Pinecone(api_key="123-456-789") + p.create_index("my-index", 10, timeout=10, cloud="aws", region="us-west1", capacity_mode="pod") + + # @pytest.mark.parametrize("timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses", [ + # # No timeout, list_indexes called twice, sleep called once + # (None, 2, 1, [["my-index", "index-1"], ["index-1"]]), + # # Timeout of 10 seconds, list_indexes called 3 times, sleep twice + # (10, 3, 2, [["my-index", "index-1"], ["my-index", "index-1"], ["index-1"]]), + # # Timeout of -1 seconds, list_indexes not called, no sleep + # (-1, 0, 0, [["my-index", "index-1"]]), + # ]) + # def test_delete_index_with_timeout(self, mocker, timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses): + # api_instance_mock = mocker.Mock() + # api_instance_mock.list_indexes = mocker.Mock(side_effect=list_indexes_responses) + # mocker.patch('pinecone.manage._get_api_instance', return_value=api_instance_mock) + # mocker.patch('time.sleep') + + # pinecone.manage.delete_index("my-index", timeout=timeout_value) + + # pinecone.manage._get_api_instance.assert_called_once() + # assert api_instance_mock.list_indexes.call_count == list_indexes_calls + # assert time.sleep.call_count == time_sleep_calls \ No newline at end of file diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 036ac126a..b98ce7687 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -4,7 +4,7 @@ import pandas as pd import pytest -import pinecone +from pinecone import Config, GRPCIndex from pinecone import DescribeIndexStatsRequest from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector, @@ -18,8 +18,7 @@ UpsertResponse, SparseValues, ) -from pinecone.utils import dict_to_proto_struct - +from pinecone.data.grpc.utils import dict_to_proto_struct class TestGrpcIndex: def setup_method(self): @@ -35,8 +34,8 @@ def setup_method(self): self.filter1 = {"genre": {"$in": ["action"]}} self.filter2 = {"year": {"$eq": 2020}} - pinecone.init(api_key="example-key") - self.index = pinecone.GRPCIndex("example-name") + self.config = Config(api_key='test-api-key', host='foo') + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") self.expected_vec1 = Vector(id="vec1", values=self.vals1, metadata={}) self.expected_vec2 = Vector(id="vec2", values=self.vals2, metadata={}) diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 28d502b39..de90bad23 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,13 +1,13 @@ import pandas as pd import numpy as np import pytest -import warnings import pinecone +from pinecone.config import PineconeConfig +from pinecone import Index from pinecone import UpsertRequest, Vector from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse, UpsertResponse, SparseValues - class TestRestIndex: def setup_method(self): self.vector_dim = 8 @@ -29,8 +29,7 @@ def setup_method(self): self.svv2 = [0.1, 0.2, 0.3] self.sv2 = {"indices": self.svi2, "values": self.svv2} - pinecone.init(api_key='example-key') - self.index = pinecone.Index('example-name') + self.index = Index(api_key='asdf', host='https://test.pinecone.io') # region: upsert tests @@ -133,7 +132,7 @@ def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): [Vector(id="vec1", values=self.vals1, metadata=self.md1)], [Vector(id="vec2", values=self.vals2, metadata=self.md2)], ] - with pinecone.Index("example-index", pool_threads=30) as index: + with Index(api_key="asdf", host="https://test.pinecone.io", pool_threads=30) as index: mocker.patch.object(index._vector_api, "upsert", autospec=True) # Send requests in parallel diff --git a/tests/unit/test_manage.py b/tests/unit/test_manage.py deleted file mode 100644 index 0a65d67ce..000000000 --- a/tests/unit/test_manage.py +++ /dev/null @@ -1,54 +0,0 @@ -import pytest -import pinecone -import time - -class TestManage: - - def test_get_api_instance_without_host(self): - pinecone.init(api_key="123-456-789", environment="my-environment") - api_instance = pinecone.manage._get_api_instance() - assert api_instance.api_client.configuration.host == "https://controller.my-environment.pinecone.io" - - def test_get_api_instance_with_host(self): - pinecone.init(api_key="123-456-789", environment="my-environment", host="my-host") - api_instance = pinecone.manage._get_api_instance() - assert api_instance.api_client.configuration.host == "my-host" - - @pytest.mark.parametrize("timeout_value, get_status_calls, time_sleep_calls, get_status_responses", [ - # No timeout, _get_status called twice, sleep called once - (None, 2, 1, [{"ready": False}, {"ready": True}]), - # Timeout of 10 seconds, _get_status called 3 times, sleep twice - (10, 3, 2, [{"ready": False}, {"ready": False}, {"ready": True}]), - # Timeout of -1 seconds, _get_status not called, no sleep - (-1, 0, 0, [{"ready": False}]), - ]) - def test_create_index_with_timeout(self, mocker, timeout_value, get_status_calls, time_sleep_calls, get_status_responses): - mocker.patch('pinecone.manage._get_api_instance', return_value=mocker.Mock()) - mocker.patch('pinecone.manage._get_status', side_effect=get_status_responses) - mocker.patch('time.sleep') - - pinecone.manage.create_index("my-index", 10, timeout=timeout_value, cloud="aws", region="us-west1", capacity_mode="pod") - - pinecone.manage._get_api_instance.assert_called_once() - assert pinecone.manage._get_status.call_count == get_status_calls - assert time.sleep.call_count == time_sleep_calls - - @pytest.mark.parametrize("timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses", [ - # No timeout, list_indexes called twice, sleep called once - (None, 2, 1, [["my-index", "index-1"], ["index-1"]]), - # Timeout of 10 seconds, list_indexes called 3 times, sleep twice - (10, 3, 2, [["my-index", "index-1"], ["my-index", "index-1"], ["index-1"]]), - # Timeout of -1 seconds, list_indexes not called, no sleep - (-1, 0, 0, [["my-index", "index-1"]]), - ]) - def test_delete_index_with_timeout(self, mocker, timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses): - api_instance_mock = mocker.Mock() - api_instance_mock.list_indexes = mocker.Mock(side_effect=list_indexes_responses) - mocker.patch('pinecone.manage._get_api_instance', return_value=api_instance_mock) - mocker.patch('time.sleep') - - pinecone.manage.delete_index("my-index", timeout=timeout_value) - - pinecone.manage._get_api_instance.assert_called_once() - assert api_instance_mock.list_indexes.call_count == list_indexes_calls - assert time.sleep.call_count == time_sleep_calls \ No newline at end of file From 70c80a8a5e792ed79b04a49cf0008c904058d9bc Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 31 Oct 2023 12:20:47 -0400 Subject: [PATCH 03/39] Downgrade to openapi 5.2, add template overrides (#229) ## Problem Recent versions of openapi generator have added dependencies we don't want to take on, especially `pydantic` v1. Pydantic v2 has been out for a while and we think this is very likely to lead to dependency clashes for some users. ## Solution The reason we updated in the first place was to avoid generating code that emitted urllib3 deprecation notices. In this PR, I downgrade to the previously used 5.2.0 generator version and address the urllib3 error using [template overrides](https://openapi-generator.tech/docs/templating/) in the generation step. In this diff: - Go back to generating the core with openapi 5.2.0 (same version as before, e.g. on main) - Everything under `pinecone/core` is generated using openapi and don't need to be specifically reviewed. This is like 90% of the files changed. - Use a template override in the generation step (handled in a private repo) to adjust the urllib3 getheaders() usage and avoid spamming those deprecation notices. - Notice that generated `rest.py` is using [correct syntax](https://stackoverflow.com/questions/75382508/deprecationwarning-httpresponse-getheader-is-deprecated-and-will-be-removed-i) for getting headers in urllib3 - Fix tests that broke along the way, mostly due to changes in package structure used by the generated code. - Remove dependencies from `pyproject.toml` that were added when previously going from openapi 5.2.0 => 7.0.1 (pydantic, aenum) ## Type of Change - [x] None of the above: Update generated code, change dependencies ## Follow-up needed - Docs build broken. By the looks of it, it seems related to numpy. But I want to remove numpy in a follow-up diff anyway so I may merge with this build failing for now. --- pinecone/config/openapi.py | 2 +- pinecone/control/pinecone.py | 4 +- pinecone/core/client/__init__.py | 53 +- pinecone/core/client/api/__init__.py | 8 +- .../core/client/api/index_operations_api.py | 2526 +++++++-------- .../core/client/api/vector_operations_api.py | 2173 ++++++------- pinecone/core/client/api_client.py | 1096 ++++--- pinecone/core/client/api_response.py | 22 - pinecone/core/client/apis/__init__.py | 18 + pinecone/core/client/configuration.py | 317 +- pinecone/core/client/exceptions.py | 46 +- pinecone/core/client/model/__init__.py | 5 + .../core/client/model/approximated_config.py | 260 ++ pinecone/core/client/model/collection_meta.py | 272 ++ .../client/model/create_collection_request.py | 268 ++ pinecone/core/client/model/create_request.py | 304 ++ pinecone/core/client/model/delete_request.py | 270 ++ .../model/describe_index_stats_request.py | 256 ++ .../model/describe_index_stats_response.py | 274 ++ pinecone/core/client/model/fetch_response.py | 266 ++ pinecone/core/client/model/hnsw_config.py | 268 ++ pinecone/core/client/model/index_meta.py | 268 ++ .../core/client/model/index_meta_database.py | 292 ++ .../core/client/model/index_meta_status.py | 278 ++ .../core/client/model/namespace_summary.py | 256 ++ pinecone/core/client/model/patch_request.py | 260 ++ pinecone/core/client/model/protobuf_any.py | 260 ++ .../core/client/model/protobuf_null_value.py | 280 ++ pinecone/core/client/model/query_request.py | 313 ++ pinecone/core/client/model/query_response.py | 272 ++ pinecone/core/client/model/query_vector.py | 290 ++ pinecone/core/client/model/rpc_status.py | 270 ++ pinecone/core/client/model/scored_vector.py | 288 ++ .../core/client/model/single_query_results.py | 266 ++ pinecone/core/client/model/sparse_values.py | 272 ++ pinecone/core/client/model/update_request.py | 290 ++ pinecone/core/client/model/upsert_request.py | 274 ++ pinecone/core/client/model/upsert_response.py | 256 ++ pinecone/core/client/model/vector.py | 288 ++ pinecone/core/client/model_utils.py | 1993 ++++++++++++ pinecone/core/client/models/__init__.py | 79 +- .../core/client/models/approximated_config.py | 74 - .../core/client/models/collection_meta.py | 79 - .../models/create_collection_request.py | 68 - pinecone/core/client/models/create_request.py | 149 - .../models/create_request_index_config.py | 140 - pinecone/core/client/models/delete_request.py | 85 - .../models/describe_index_stats_request.py | 71 - .../models/describe_index_stats_response.py | 95 - pinecone/core/client/models/fetch_response.py | 84 - pinecone/core/client/models/hnsw_config.py | 78 - pinecone/core/client/models/index_meta.py | 83 - .../core/client/models/index_meta_database.py | 110 - .../index_meta_database_index_config.py | 140 - .../core/client/models/index_meta_status.py | 90 - .../client/models/list_indexes200_response.py | 82 - .../core/client/models/namespace_summary.py | 72 - pinecone/core/client/models/patch_request.py | 72 - pinecone/core/client/models/protobuf_any.py | 69 - .../core/client/models/protobuf_null_value.py | 35 - pinecone/core/client/models/query_request.py | 134 - pinecone/core/client/models/query_response.py | 98 - pinecone/core/client/models/query_vector.py | 93 - pinecone/core/client/models/rpc_status.py | 86 - pinecone/core/client/models/scored_vector.py | 91 - .../client/models/single_query_results.py | 84 - pinecone/core/client/models/sparse_values.py | 72 - pinecone/core/client/models/update_request.py | 88 - pinecone/core/client/models/upsert_request.py | 86 - .../core/client/models/upsert_response.py | 70 - pinecone/core/client/models/vector.py | 86 - pinecone/core/client/py.typed | 0 pinecone/core/client/rest.py | 306 +- .../core/grpc/protos/vector_service_pb2.py | 2843 +++++++---------- .../core/grpc/protos/vector_service_pb2.pyi | 435 +-- .../grpc/protos/vector_service_pb2_grpc.py | 354 +- pinecone/data/index.py | 8 +- poetry.lock | 66 +- pyproject.toml | 2 - tests/unit/test_control.py | 40 +- tests/unit/test_index.py | 2 - 81 files changed, 13853 insertions(+), 8620 deletions(-) delete mode 100644 pinecone/core/client/api_response.py create mode 100644 pinecone/core/client/apis/__init__.py create mode 100644 pinecone/core/client/model/__init__.py create mode 100644 pinecone/core/client/model/approximated_config.py create mode 100644 pinecone/core/client/model/collection_meta.py create mode 100644 pinecone/core/client/model/create_collection_request.py create mode 100644 pinecone/core/client/model/create_request.py create mode 100644 pinecone/core/client/model/delete_request.py create mode 100644 pinecone/core/client/model/describe_index_stats_request.py create mode 100644 pinecone/core/client/model/describe_index_stats_response.py create mode 100644 pinecone/core/client/model/fetch_response.py create mode 100644 pinecone/core/client/model/hnsw_config.py create mode 100644 pinecone/core/client/model/index_meta.py create mode 100644 pinecone/core/client/model/index_meta_database.py create mode 100644 pinecone/core/client/model/index_meta_status.py create mode 100644 pinecone/core/client/model/namespace_summary.py create mode 100644 pinecone/core/client/model/patch_request.py create mode 100644 pinecone/core/client/model/protobuf_any.py create mode 100644 pinecone/core/client/model/protobuf_null_value.py create mode 100644 pinecone/core/client/model/query_request.py create mode 100644 pinecone/core/client/model/query_response.py create mode 100644 pinecone/core/client/model/query_vector.py create mode 100644 pinecone/core/client/model/rpc_status.py create mode 100644 pinecone/core/client/model/scored_vector.py create mode 100644 pinecone/core/client/model/single_query_results.py create mode 100644 pinecone/core/client/model/sparse_values.py create mode 100644 pinecone/core/client/model/update_request.py create mode 100644 pinecone/core/client/model/upsert_request.py create mode 100644 pinecone/core/client/model/upsert_response.py create mode 100644 pinecone/core/client/model/vector.py create mode 100644 pinecone/core/client/model_utils.py delete mode 100644 pinecone/core/client/models/approximated_config.py delete mode 100644 pinecone/core/client/models/collection_meta.py delete mode 100644 pinecone/core/client/models/create_collection_request.py delete mode 100644 pinecone/core/client/models/create_request.py delete mode 100644 pinecone/core/client/models/create_request_index_config.py delete mode 100644 pinecone/core/client/models/delete_request.py delete mode 100644 pinecone/core/client/models/describe_index_stats_request.py delete mode 100644 pinecone/core/client/models/describe_index_stats_response.py delete mode 100644 pinecone/core/client/models/fetch_response.py delete mode 100644 pinecone/core/client/models/hnsw_config.py delete mode 100644 pinecone/core/client/models/index_meta.py delete mode 100644 pinecone/core/client/models/index_meta_database.py delete mode 100644 pinecone/core/client/models/index_meta_database_index_config.py delete mode 100644 pinecone/core/client/models/index_meta_status.py delete mode 100644 pinecone/core/client/models/list_indexes200_response.py delete mode 100644 pinecone/core/client/models/namespace_summary.py delete mode 100644 pinecone/core/client/models/patch_request.py delete mode 100644 pinecone/core/client/models/protobuf_any.py delete mode 100644 pinecone/core/client/models/protobuf_null_value.py delete mode 100644 pinecone/core/client/models/query_request.py delete mode 100644 pinecone/core/client/models/query_response.py delete mode 100644 pinecone/core/client/models/query_vector.py delete mode 100644 pinecone/core/client/models/rpc_status.py delete mode 100644 pinecone/core/client/models/scored_vector.py delete mode 100644 pinecone/core/client/models/single_query_results.py delete mode 100644 pinecone/core/client/models/sparse_values.py delete mode 100644 pinecone/core/client/models/update_request.py delete mode 100644 pinecone/core/client/models/upsert_request.py delete mode 100644 pinecone/core/client/models/upsert_response.py delete mode 100644 pinecone/core/client/models/vector.py delete mode 100644 pinecone/core/client/py.typed diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index 952a672de..83f9a9cca 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -17,7 +17,7 @@ class OpenApiConfigFactory: @classmethod def build(cls, api_key: str, host: str = None, **kwargs): - openapi_config = OpenApiConfiguration.get_default() + openapi_config = OpenApiConfiguration() openapi_config.host = host openapi_config.ssl_ca_cert = certifi.where() openapi_config.socket_options = cls._get_socket_options() diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index c6d3037b0..535b087e8 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -10,9 +10,7 @@ from pinecone.core.client.api.index_operations_api import IndexOperationsApi from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.models.create_request import CreateRequest -from pinecone.core.client.models.patch_request import PatchRequest -from pinecone.core.client.models.create_collection_request import CreateCollectionRequest +from pinecone.core.client.models import CreateCollectionRequest, CreateRequest, PatchRequest from pinecone.utils import get_user_agent from pinecone.data import Index diff --git a/pinecone/core/client/__init__.py b/pinecone/core/client/__init__.py index 3e4f7ad7e..584d1219b 100644 --- a/pinecone/core/client/__init__.py +++ b/pinecone/core/client/__init__.py @@ -1,65 +1,28 @@ -# coding: utf-8 - # flake8: noqa """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" __version__ = "1.0.0" -# import apis into sdk package -from pinecone.core.client.api.index_operations_api import IndexOperationsApi -from pinecone.core.client.api.vector_operations_api import VectorOperationsApi - # import ApiClient -from pinecone.core.client.api_response import ApiResponse from pinecone.core.client.api_client import ApiClient + +# import Configuration from pinecone.core.client.configuration import Configuration + +# import exceptions from pinecone.core.client.exceptions import OpenApiException +from pinecone.core.client.exceptions import ApiAttributeError from pinecone.core.client.exceptions import ApiTypeError from pinecone.core.client.exceptions import ApiValueError from pinecone.core.client.exceptions import ApiKeyError -from pinecone.core.client.exceptions import ApiAttributeError from pinecone.core.client.exceptions import ApiException - -# import models into sdk package -from pinecone.core.client.models.approximated_config import ApproximatedConfig -from pinecone.core.client.models.collection_meta import CollectionMeta -from pinecone.core.client.models.create_collection_request import CreateCollectionRequest -from pinecone.core.client.models.create_request import CreateRequest -from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig -from pinecone.core.client.models.delete_request import DeleteRequest -from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.models.fetch_response import FetchResponse -from pinecone.core.client.models.hnsw_config import HnswConfig -from pinecone.core.client.models.index_meta import IndexMeta -from pinecone.core.client.models.index_meta_database import IndexMetaDatabase -from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig -from pinecone.core.client.models.index_meta_status import IndexMetaStatus -from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response -from pinecone.core.client.models.namespace_summary import NamespaceSummary -from pinecone.core.client.models.patch_request import PatchRequest -from pinecone.core.client.models.protobuf_any import ProtobufAny -from pinecone.core.client.models.protobuf_null_value import ProtobufNullValue -from pinecone.core.client.models.query_request import QueryRequest -from pinecone.core.client.models.query_response import QueryResponse -from pinecone.core.client.models.query_vector import QueryVector -from pinecone.core.client.models.rpc_status import RpcStatus -from pinecone.core.client.models.scored_vector import ScoredVector -from pinecone.core.client.models.single_query_results import SingleQueryResults -from pinecone.core.client.models.sparse_values import SparseValues -from pinecone.core.client.models.update_request import UpdateRequest -from pinecone.core.client.models.upsert_request import UpsertRequest -from pinecone.core.client.models.upsert_response import UpsertResponse -from pinecone.core.client.models.vector import Vector diff --git a/pinecone/core/client/api/__init__.py b/pinecone/core/client/api/__init__.py index dc3b0a5bf..14e304372 100644 --- a/pinecone/core/client/api/__init__.py +++ b/pinecone/core/client/api/__init__.py @@ -1,5 +1,3 @@ -# flake8: noqa - -# import apis into api package -from pinecone.core.client.api.index_operations_api import IndexOperationsApi -from pinecone.core.client.api.vector_operations_api import VectorOperationsApi +# do not import all apis into this module because that uses a lot of memory and stack frames +# if you need the ability to import all apis from one package, import them with +# from pinecone.core.client.apis import IndexOperationsApi diff --git a/pinecone/core/client/api/index_operations_api.py b/pinecone/core/client/api/index_operations_api.py index 52f581780..152af5ad2 100644 --- a/pinecone/core/client/api/index_operations_api.py +++ b/pinecone/core/client/api/index_operations_api.py @@ -1,1411 +1,1185 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError - -from typing_extensions import Annotated -from pydantic import Field, StrictStr - -from typing import List, Optional - -from pinecone.core.client.models.collection_meta import CollectionMeta -from pinecone.core.client.models.create_collection_request import CreateCollectionRequest -from pinecone.core.client.models.create_request import CreateRequest -from pinecone.core.client.models.index_meta import IndexMeta -from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response -from pinecone.core.client.models.patch_request import PatchRequest - -from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.api_response import ApiResponse -from pinecone.core.client.exceptions import ApiTypeError, ApiValueError # noqa: F401 - - -class IndexOperationsApi: +import sys # noqa: F401 + +from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.client.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from pinecone.core.client.model.collection_meta import CollectionMeta +from pinecone.core.client.model.create_collection_request import CreateCollectionRequest +from pinecone.core.client.model.create_request import CreateRequest +from pinecone.core.client.model.index_meta import IndexMeta +from pinecone.core.client.model.patch_request import PatchRequest + + +class IndexOperationsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None) -> None: + def __init__(self, api_client=None): if api_client is None: - api_client = ApiClient.get_default() + api_client = ApiClient() self.api_client = api_client - @validate_arguments - def configure_index( - self, - index_name: Annotated[StrictStr, Field(..., description="The name of the index")], - patch_request: Annotated[ - Optional[PatchRequest], Field(description="The desired pod type and replica configuration for the index.") - ] = None, - **kwargs, - ) -> IndexMeta: # noqa: E501 - """configure_index # noqa: E501 - - This operation specifies the pod type and number of replicas for an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.configure_index(index_name, patch_request, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param patch_request: The desired pod type and replica configuration for the index. - :type patch_request: PatchRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: IndexMeta - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the configure_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.configure_index_with_http_info(index_name, patch_request, **kwargs) # noqa: E501 - - @validate_arguments - def configure_index_with_http_info( - self, - index_name: Annotated[StrictStr, Field(..., description="The name of the index")], - patch_request: Annotated[ - Optional[PatchRequest], Field(description="The desired pod type and replica configuration for the index.") - ] = None, - **kwargs, - ) -> ApiResponse: # noqa: E501 - """configure_index # noqa: E501 - - This operation specifies the pod type and number of replicas for an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.configure_index_with_http_info(index_name, patch_request, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param patch_request: The desired pod type and replica configuration for the index. - :type patch_request: PatchRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["index_name", "patch_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method configure_index" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params["index_name"]: - _path_params["indexName"] = _params["index_name"] - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["patch_request"] is not None: - _body_params = _params["patch_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "202": "IndexMeta", - "400": None, - "404": None, - "500": None, - } - - return self.api_client.call_api( - "/databases/{indexName}", - "PATCH", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def create_collection( - self, create_collection_request: Optional[CreateCollectionRequest] = None, **kwargs - ) -> str: # noqa: E501 - """create_collection # noqa: E501 - - This operation creates a Pinecone collection. # 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_collection(create_collection_request, async_req=True) - >>> result = thread.get() - - :param create_collection_request: - :type create_collection_request: CreateCollectionRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the create_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.create_collection_with_http_info(create_collection_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_collection_with_http_info( - self, create_collection_request: Optional[CreateCollectionRequest] = None, **kwargs - ) -> ApiResponse: # noqa: E501 - """create_collection # noqa: E501 - - This operation creates a Pinecone collection. # 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_collection_with_http_info(create_collection_request, async_req=True) - >>> result = thread.get() - - :param create_collection_request: - :type create_collection_request: CreateCollectionRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["create_collection_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_collection" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["create_collection_request"] is not None: - _body_params = _params["create_collection_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "201": "str", - "400": None, - "409": None, - "500": None, - } - - return self.api_client.call_api( - "/collections", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def create_index(self, create_request: Optional[CreateRequest] = None, **kwargs) -> IndexMeta: # noqa: E501 - """create_index # noqa: E501 - - This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # 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(create_request, async_req=True) - >>> result = thread.get() - - :param create_request: - :type create_request: CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: IndexMeta - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the create_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.create_index_with_http_info(create_request, **kwargs) # noqa: E501 - - @validate_arguments - def create_index_with_http_info( - self, create_request: Optional[CreateRequest] = None, **kwargs - ) -> ApiResponse: # noqa: E501 - """create_index # noqa: E501 - - This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # 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_with_http_info(create_request, async_req=True) - >>> result = thread.get() - - :param create_request: - :type create_request: CreateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["create_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_index" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["create_request"] is not None: - _body_params = _params["create_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "201": "IndexMeta", - "400": None, - "409": None, - "500": None, - } - - return self.api_client.call_api( - "/databases", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def delete_collection( - self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs - ) -> str: # noqa: E501 - """delete_collection # noqa: E501 - - This operation deletes an existing collection. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_collection(collection_name, async_req=True) - >>> result = thread.get() - - :param collection_name: The name of the collection (required) - :type collection_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the delete_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.delete_collection_with_http_info(collection_name, **kwargs) # noqa: E501 - - @validate_arguments - def delete_collection_with_http_info( - self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs - ) -> ApiResponse: # noqa: E501 - """delete_collection # noqa: E501 - - This operation deletes an existing collection. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_collection_with_http_info(collection_name, async_req=True) - >>> result = thread.get() - - :param collection_name: The name of the collection (required) - :type collection_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["collection_name"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete_collection" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params["collection_name"]: - _path_params["collectionName"] = _params["collection_name"] - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "202": "str", - "404": None, - "500": None, - } - - return self.api_client.call_api( - "/collections/{collectionName}", - "DELETE", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def delete_index( - self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs - ) -> str: # noqa: E501 - """delete_index # noqa: E501 - - This operation deletes an existing index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_index(index_name, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the delete_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.delete_index_with_http_info(index_name, **kwargs) # noqa: E501 - - @validate_arguments - def delete_index_with_http_info( - self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs - ) -> ApiResponse: # noqa: E501 - """delete_index # noqa: E501 - - This operation deletes an existing index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_index_with_http_info(index_name, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["index_name"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete_index" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params["index_name"]: - _path_params["indexName"] = _params["index_name"] - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["text/plain"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "202": "str", - "404": None, - "500": None, - } - - return self.api_client.call_api( - "/databases/{indexName}", - "DELETE", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __configure_index( + self, + index_name, + **kwargs + ): + """configure_index # noqa: E501 + + This operation specifies the pod type and number of replicas for an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.configure_index(index_name, async_req=True) + >>> result = thread.get() + + Args: + index_name (str): The name of the index + + Keyword Args: + patch_request (PatchRequest): The desired pod type and replica configuration for the index.. [optional] + _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: + str + 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['index_name'] = \ + index_name + return self.call_with_http_info(**kwargs) + + self.configure_index = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/databases/{indexName}', + 'operation_id': 'configure_index', + 'http_method': 'PATCH', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'index_name', + 'patch_request', + ], + 'required': [ + 'index_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'index_name': + (str,), + 'patch_request': + (PatchRequest,), + }, + 'attribute_map': { + 'index_name': 'indexName', + }, + 'location_map': { + 'index_name': 'path', + 'patch_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'text/plain' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__configure_index ) - @validate_arguments - def describe_collection( - self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs - ) -> CollectionMeta: # noqa: E501 - """describe_collection # noqa: E501 - - Get a description of a collection. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_collection(collection_name, async_req=True) - >>> result = thread.get() - - :param collection_name: The name of the collection (required) - :type collection_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: CollectionMeta - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the describe_collection_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.describe_collection_with_http_info(collection_name, **kwargs) # noqa: E501 - - @validate_arguments - def describe_collection_with_http_info( - self, collection_name: Annotated[StrictStr, Field(..., description="The name of the collection")], **kwargs - ) -> ApiResponse: # noqa: E501 - """describe_collection # noqa: E501 - - Get a description of a collection. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_collection_with_http_info(collection_name, async_req=True) - >>> result = thread.get() - - :param collection_name: The name of the collection (required) - :type collection_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(CollectionMeta, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["collection_name"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __create_collection( + self, + **kwargs + ): + """create_collection # noqa: E501 + + This operation creates a Pinecone collection. # 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_collection(async_req=True) + >>> result = thread.get() + + + Keyword Args: + create_collection_request (CreateCollectionRequest): [optional] + _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: + str + 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') + return self.call_with_http_info(**kwargs) + + self.create_collection = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/collections', + 'operation_id': 'create_collection', + 'http_method': 'POST', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'create_collection_request', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'create_collection_request': + (CreateCollectionRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'create_collection_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'text/plain' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__create_collection ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_collection" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params["collection_name"]: - _path_params["collectionName"] = _params["collection_name"] - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "CollectionMeta", - "404": None, - "500": None, - } - - return self.api_client.call_api( - "/collections/{collectionName}", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __create_index( + self, + **kwargs + ): + """create_index # noqa: E501 + + This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # 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(async_req=True) + >>> result = thread.get() + + + Keyword Args: + create_request (CreateRequest): [optional] + _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: + str + 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') + return self.call_with_http_info(**kwargs) + + self.create_index = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/databases', + 'operation_id': 'create_index', + 'http_method': 'POST', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'create_request', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'create_request': + (CreateRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'create_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'text/plain' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__create_index ) - @validate_arguments - def describe_index( - self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs - ) -> IndexMeta: # noqa: E501 - """describe_index # noqa: E501 - - Get a description of an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index(index_name, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: IndexMeta - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the describe_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.describe_index_with_http_info(index_name, **kwargs) # noqa: E501 - - @validate_arguments - def describe_index_with_http_info( - self, index_name: Annotated[StrictStr, Field(..., description="The name of the index")], **kwargs - ) -> ApiResponse: # noqa: E501 - """describe_index # noqa: E501 - - Get a description of an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index_with_http_info(index_name, async_req=True) - >>> result = thread.get() - - :param index_name: The name of the index (required) - :type index_name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(IndexMeta, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = ["index_name"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __delete_collection( + self, + collection_name, + **kwargs + ): + """delete_collection # noqa: E501 + + This operation deletes an existing collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_collection(collection_name, async_req=True) + >>> result = thread.get() + + Args: + collection_name (str): The name of the collection + + 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: + str + 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['collection_name'] = \ + collection_name + return self.call_with_http_info(**kwargs) + + self.delete_collection = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/collections/{collectionName}', + 'operation_id': 'delete_collection', + 'http_method': 'DELETE', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'collection_name', + ], + 'required': [ + 'collection_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'collection_name': + (str,), + }, + 'attribute_map': { + 'collection_name': 'collectionName', + }, + 'location_map': { + 'collection_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'text/plain' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_collection ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - if _params["index_name"]: - _path_params["indexName"] = _params["index_name"] - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "IndexMeta", - "404": None, - "500": None, - } - - return self.api_client.call_api( - "/databases/{indexName}", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __delete_index( + self, + index_name, + **kwargs + ): + """delete_index # noqa: E501 + + This operation deletes an existing index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_index(index_name, async_req=True) + >>> result = thread.get() + + Args: + index_name (str): The name of the index + + 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: + str + 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['index_name'] = \ + index_name + return self.call_with_http_info(**kwargs) + + self.delete_index = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/databases/{indexName}', + 'operation_id': 'delete_index', + 'http_method': 'DELETE', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'index_name', + ], + 'required': [ + 'index_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'index_name': + (str,), + }, + 'attribute_map': { + 'index_name': 'indexName', + }, + 'location_map': { + 'index_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'text/plain' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_index ) - @validate_arguments - def list_collections(self, **kwargs) -> List[str]: # noqa: E501 - """list_collections # noqa: E501 - - This operation returns a list of your Pinecone collections. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_collections(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[str] - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the list_collections_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.list_collections_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def list_collections_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """list_collections # noqa: E501 - - This operation returns a list of your Pinecone collections. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_collections_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[str], status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = [] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __describe_collection( + self, + collection_name, + **kwargs + ): + """describe_collection # noqa: E501 + + Get a description of a collection. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_collection(collection_name, async_req=True) + >>> result = thread.get() + + Args: + collection_name (str): The name of the collection + + 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: + CollectionMeta + 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['collection_name'] = \ + collection_name + return self.call_with_http_info(**kwargs) + + self.describe_collection = _Endpoint( + settings={ + 'response_type': (CollectionMeta,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/collections/{collectionName}', + 'operation_id': 'describe_collection', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'collection_name', + ], + 'required': [ + 'collection_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'collection_name': + (str,), + }, + 'attribute_map': { + 'collection_name': 'collectionName', + }, + 'location_map': { + 'collection_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__describe_collection ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method list_collections" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept( - ["application/json; charset=utf-8"] - ) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "List[str]", - } - - return self.api_client.call_api( - "/collections", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __describe_index( + self, + index_name, + **kwargs + ): + """describe_index # noqa: E501 + + Get a description of an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index(index_name, async_req=True) + >>> result = thread.get() + + Args: + index_name (str): The name of the index + + 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: + IndexMeta + 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['index_name'] = \ + index_name + return self.call_with_http_info(**kwargs) + + self.describe_index = _Endpoint( + settings={ + 'response_type': (IndexMeta,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/databases/{indexName}', + 'operation_id': 'describe_index', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + 'index_name', + ], + 'required': [ + 'index_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'index_name': + (str,), + }, + 'attribute_map': { + 'index_name': 'indexName', + }, + 'location_map': { + 'index_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__describe_index ) - @validate_arguments - def list_indexes(self, **kwargs) -> ListIndexes200Response: # noqa: E501 - """list_indexes # noqa: E501 - - This operation returns a list of your Pinecone indexes. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_indexes(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ListIndexes200Response - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the list_indexes_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.list_indexes_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def list_indexes_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """list_indexes # noqa: E501 - - This operation returns a list of your Pinecone indexes. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_indexes_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ListIndexes200Response, status_code(int), headers(HTTPHeaderDict)) - """ - - _hosts = ["https://api.pinecone.io"] - _host = _hosts[0] - if kwargs.get("_host_index"): - _host_index = int(kwargs.get("_host_index")) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(_host)) - _host = _hosts[_host_index] - _params = locals() - - _all_params = [] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __list_collections( + self, + **kwargs + ): + """list_collections # noqa: E501 + + This operation returns a list of your Pinecone collections. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_collections(async_req=True) + >>> result = thread.get() + + + 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: + [str] + 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') + return self.call_with_http_info(**kwargs) + + self.list_collections = _Endpoint( + settings={ + 'response_type': ([str],), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/collections', + 'operation_id': 'list_collections', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json; charset=utf-8' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__list_collections ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method list_indexes" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept( - ["application/json; charset=utf-8"] - ) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "ListIndexes200Response", - } - - return self.api_client.call_api( - "/databases", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - _host=_host, - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __list_indexes( + self, + **kwargs + ): + """list_indexes # noqa: E501 + + This operation returns a list of your Pinecone indexes. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_indexes(async_req=True) + >>> result = thread.get() + + + 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: + [str] + 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') + return self.call_with_http_info(**kwargs) + + self.list_indexes = _Endpoint( + settings={ + 'response_type': ([str],), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/databases', + 'operation_id': 'list_indexes', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://controller.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } + }, + ] + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json; charset=utf-8' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__list_indexes ) diff --git a/pinecone/core/client/api/vector_operations_api.py b/pinecone/core/client/api/vector_operations_api.py index 98c1d1a6d..c5bc02a2a 100644 --- a/pinecone/core/client/api/vector_operations_api.py +++ b/pinecone/core/client/api/vector_operations_api.py @@ -1,1233 +1,1006 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError - -from typing_extensions import Annotated -from pydantic import Field, StrictBool, StrictStr, conlist - -from typing import Any, Dict, Optional - -from pinecone.core.client.models.delete_request import DeleteRequest -from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.models.fetch_response import FetchResponse -from pinecone.core.client.models.query_request import QueryRequest -from pinecone.core.client.models.query_response import QueryResponse -from pinecone.core.client.models.update_request import UpdateRequest -from pinecone.core.client.models.upsert_request import UpsertRequest -from pinecone.core.client.models.upsert_response import UpsertResponse - -from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.api_response import ApiResponse -from pinecone.core.client.exceptions import ApiTypeError, ApiValueError # noqa: F401 - - -class VectorOperationsApi: +import sys # noqa: F401 + +from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.client.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from pinecone.core.client.model.delete_request import DeleteRequest +from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.model.fetch_response import FetchResponse +from pinecone.core.client.model.query_request import QueryRequest +from pinecone.core.client.model.query_response import QueryResponse +from pinecone.core.client.model.rpc_status import RpcStatus +from pinecone.core.client.model.update_request import UpdateRequest +from pinecone.core.client.model.upsert_request import UpsertRequest +from pinecone.core.client.model.upsert_response import UpsertResponse + + +class VectorOperationsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None) -> None: + def __init__(self, api_client=None): if api_client is None: - api_client = ApiClient.get_default() + api_client = ApiClient() self.api_client = api_client - @validate_arguments - def delete(self, delete_request: DeleteRequest, **kwargs) -> object: # noqa: E501 - """Delete # noqa: E501 - - The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete(delete_request, async_req=True) - >>> result = thread.get() - - :param delete_request: (required) - :type delete_request: DeleteRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: object - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the delete_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.delete_with_http_info(delete_request, **kwargs) # noqa: E501 - - @validate_arguments - def delete_with_http_info(self, delete_request: DeleteRequest, **kwargs) -> ApiResponse: # noqa: E501 - """Delete # noqa: E501 - - The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete_with_http_info(delete_request, async_req=True) - >>> result = thread.get() - - :param delete_request: (required) - :type delete_request: DeleteRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["delete_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["delete_request"] is not None: - _body_params = _params["delete_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "object", - } - - return self.api_client.call_api( - "/vectors/delete", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def delete1( - self, - ids: Annotated[Optional[conlist(StrictStr)], Field(description="Vectors to delete.")] = None, - delete_all: Annotated[ - Optional[StrictBool], - Field(description="This indicates that all vectors in the index namespace should be deleted."), - ] = None, - namespace: Annotated[ - Optional[StrictStr], Field(description="The namespace to delete vectors from, if applicable.") - ] = None, - **kwargs, - ) -> object: # noqa: E501 - """Delete # noqa: E501 - - The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete1(ids, delete_all, namespace, async_req=True) - >>> result = thread.get() - - :param ids: Vectors to delete. - :type ids: List[str] - :param delete_all: This indicates that all vectors in the index namespace should be deleted. - :type delete_all: bool - :param namespace: The namespace to delete vectors from, if applicable. - :type namespace: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: object - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the delete1_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.delete1_with_http_info(ids, delete_all, namespace, **kwargs) # noqa: E501 - - @validate_arguments - def delete1_with_http_info( - self, - ids: Annotated[Optional[conlist(StrictStr)], Field(description="Vectors to delete.")] = None, - delete_all: Annotated[ - Optional[StrictBool], - Field(description="This indicates that all vectors in the index namespace should be deleted."), - ] = None, - namespace: Annotated[ - Optional[StrictStr], Field(description="The namespace to delete vectors from, if applicable.") - ] = None, - **kwargs, - ) -> ApiResponse: # noqa: E501 - """Delete # noqa: E501 - - The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete1_with_http_info(ids, delete_all, namespace, async_req=True) - >>> result = thread.get() - - :param ids: Vectors to delete. - :type ids: List[str] - :param delete_all: This indicates that all vectors in the index namespace should be deleted. - :type delete_all: bool - :param namespace: The namespace to delete vectors from, if applicable. - :type namespace: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["ids", "delete_all", "namespace"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __delete( + self, + delete_request, + **kwargs + ): + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete(delete_request, async_req=True) + >>> result = thread.get() + + Args: + delete_request (DeleteRequest): + + 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: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + 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['delete_request'] = \ + delete_request + return self.call_with_http_info(**kwargs) + + self.delete = _Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/vectors/delete', + 'operation_id': 'delete', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'delete_request', + ], + 'required': [ + 'delete_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'delete_request': + (DeleteRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'delete_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__delete ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method delete1" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get("ids") is not None: # noqa: E501 - _query_params.append(("ids", _params["ids"])) - _collection_formats["ids"] = "multi" - - if _params.get("delete_all") is not None: # noqa: E501 - _query_params.append(("deleteAll", _params["delete_all"])) - - if _params.get("namespace") is not None: # noqa: E501 - _query_params.append(("namespace", _params["namespace"])) - - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "object", - } - - return self.api_client.call_api( - "/vectors/delete", - "DELETE", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __delete1( + self, + **kwargs + ): + """Delete # noqa: E501 + + The `Delete` operation deletes vectors, by id, from a single namespace. You can delete items by their id, from a single 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.delete1(async_req=True) + >>> result = thread.get() + + + Keyword Args: + ids ([str]): Vectors to delete.. [optional] + 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 + namespace (str): The namespace to delete vectors from, if applicable.. [optional] + _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: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + 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') + return self.call_with_http_info(**kwargs) + + self.delete1 = _Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/vectors/delete', + 'operation_id': 'delete1', + 'http_method': 'DELETE', + 'servers': None, + }, + params_map={ + 'all': [ + 'ids', + 'delete_all', + 'namespace', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'ids': + ([str],), + 'delete_all': + (bool,), + 'namespace': + (str,), + }, + 'attribute_map': { + 'ids': 'ids', + 'delete_all': 'deleteAll', + 'namespace': 'namespace', + }, + 'location_map': { + 'ids': 'query', + 'delete_all': 'query', + 'namespace': 'query', + }, + 'collection_format_map': { + 'ids': 'multi', + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__delete1 ) - @validate_arguments - def describe_index_stats( - self, describe_index_stats_request: DescribeIndexStatsRequest, **kwargs - ) -> DescribeIndexStatsResponse: # noqa: E501 - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index_stats(describe_index_stats_request, async_req=True) - >>> result = thread.get() - - :param describe_index_stats_request: (required) - :type describe_index_stats_request: DescribeIndexStatsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DescribeIndexStatsResponse - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the describe_index_stats_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.describe_index_stats_with_http_info(describe_index_stats_request, **kwargs) # noqa: E501 - - @validate_arguments - def describe_index_stats_with_http_info( - self, describe_index_stats_request: DescribeIndexStatsRequest, **kwargs - ) -> ApiResponse: # noqa: E501 - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index_stats_with_http_info(describe_index_stats_request, async_req=True) - >>> result = thread.get() - - :param describe_index_stats_request: (required) - :type describe_index_stats_request: DescribeIndexStatsRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DescribeIndexStatsResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["describe_index_stats_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __describe_index_stats( + self, + describe_index_stats_request, + **kwargs + ): + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats(describe_index_stats_request, async_req=True) + >>> result = thread.get() + + Args: + describe_index_stats_request (DescribeIndexStatsRequest): + + 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: + DescribeIndexStatsResponse + 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['describe_index_stats_request'] = \ + describe_index_stats_request + return self.call_with_http_info(**kwargs) + + self.describe_index_stats = _Endpoint( + settings={ + 'response_type': (DescribeIndexStatsResponse,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/describe_index_stats', + 'operation_id': 'describe_index_stats', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'describe_index_stats_request', + ], + 'required': [ + 'describe_index_stats_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'describe_index_stats_request': + (DescribeIndexStatsRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'describe_index_stats_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__describe_index_stats ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index_stats" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["describe_index_stats_request"] is not None: - _body_params = _params["describe_index_stats_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "DescribeIndexStatsResponse", - } - - return self.api_client.call_api( - "/describe_index_stats", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def describe_index_stats1(self, **kwargs) -> DescribeIndexStatsResponse: # noqa: E501 - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index_stats1(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: DescribeIndexStatsResponse - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the describe_index_stats1_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.describe_index_stats1_with_http_info(**kwargs) # noqa: E501 - - @validate_arguments - def describe_index_stats1_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """DescribeIndexStats # noqa: E501 - - The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index_stats1_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(DescribeIndexStatsResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method describe_index_stats1" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "DescribeIndexStatsResponse", - } - - return self.api_client.call_api( - "/describe_index_stats", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def fetch( - self, - ids: Annotated[ - conlist(StrictStr), - Field(..., description="The vector IDs to fetch. Does not accept values containing spaces."), - ], - namespace: Optional[StrictStr] = None, - **kwargs, - ) -> FetchResponse: # noqa: E501 - """Fetch # noqa: E501 - - The `Fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.fetch(ids, namespace, async_req=True) - >>> result = thread.get() - - :param ids: The vector IDs to fetch. Does not accept values containing spaces. (required) - :type ids: List[str] - :param namespace: - :type namespace: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: FetchResponse - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the fetch_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.fetch_with_http_info(ids, namespace, **kwargs) # noqa: E501 - - @validate_arguments - def fetch_with_http_info( - self, - ids: Annotated[ - conlist(StrictStr), - Field(..., description="The vector IDs to fetch. Does not accept values containing spaces."), - ], - namespace: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: # noqa: E501 - """Fetch # noqa: E501 - - The `Fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.fetch_with_http_info(ids, namespace, async_req=True) - >>> result = thread.get() - - :param ids: The vector IDs to fetch. Does not accept values containing spaces. (required) - :type ids: List[str] - :param namespace: - :type namespace: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(FetchResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["ids", "namespace"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method fetch" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - if _params.get("ids") is not None: # noqa: E501 - _query_params.append(("ids", _params["ids"])) - _collection_formats["ids"] = "multi" - - if _params.get("namespace") is not None: # noqa: E501 - _query_params.append(("namespace", _params["namespace"])) - - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "FetchResponse", - } - - return self.api_client.call_api( - "/vectors/fetch", - "GET", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), - ) - - @validate_arguments - def query(self, query_request: QueryRequest, **kwargs) -> QueryResponse: # noqa: E501 - """Query # noqa: E501 - - 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. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.query(query_request, async_req=True) - >>> result = thread.get() - - :param query_request: (required) - :type query_request: QueryRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: QueryResponse - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the query_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.query_with_http_info(query_request, **kwargs) # noqa: E501 - - @validate_arguments - def query_with_http_info(self, query_request: QueryRequest, **kwargs) -> ApiResponse: # noqa: E501 - """Query # noqa: E501 - - 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. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.query_with_http_info(query_request, async_req=True) - >>> result = thread.get() - - :param query_request: (required) - :type query_request: QueryRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(QueryResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["query_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] - ) - - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method query" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["query_request"] is not None: - _body_params = _params["query_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "QueryResponse", - } - - return self.api_client.call_api( - "/query", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __describe_index_stats1( + self, + **kwargs + ): + """DescribeIndexStats # noqa: E501 + + The `DescribeIndexStats` operation returns statistics about the index's contents, including the vector count per namespace, the number of dimensions, and the index fullness. 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/). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index_stats1(async_req=True) + >>> result = thread.get() + + + 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: + DescribeIndexStatsResponse + 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') + return self.call_with_http_info(**kwargs) + + self.describe_index_stats1 = _Endpoint( + settings={ + 'response_type': (DescribeIndexStatsResponse,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/describe_index_stats', + 'operation_id': 'describe_index_stats1', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__describe_index_stats1 ) - @validate_arguments - def update(self, update_request: UpdateRequest, **kwargs) -> object: # noqa: E501 - """Update # noqa: E501 - - The `Update` operation updates 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. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update(update_request, async_req=True) - >>> result = thread.get() - - :param update_request: (required) - :type update_request: UpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: object - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the update_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.update_with_http_info(update_request, **kwargs) # noqa: E501 - - @validate_arguments - def update_with_http_info(self, update_request: UpdateRequest, **kwargs) -> ApiResponse: # noqa: E501 - """Update # noqa: E501 - - The `Update` operation updates 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. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_with_http_info(update_request, async_req=True) - >>> result = thread.get() - - :param update_request: (required) - :type update_request: UpdateRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["update_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __fetch( + self, + ids, + **kwargs + ): + """Fetch # noqa: E501 + + The `Fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.fetch(ids, async_req=True) + >>> result = thread.get() + + Args: + ids ([str]): The vector IDs to fetch. Does not accept values containing spaces. + + Keyword Args: + namespace (str): [optional] + _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: + FetchResponse + 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['ids'] = \ + ids + return self.call_with_http_info(**kwargs) + + self.fetch = _Endpoint( + settings={ + 'response_type': (FetchResponse,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/vectors/fetch', + 'operation_id': 'fetch', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'ids', + 'namespace', + ], + 'required': [ + 'ids', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'ids': + ([str],), + 'namespace': + (str,), + }, + 'attribute_map': { + 'ids': 'ids', + 'namespace': 'namespace', + }, + 'location_map': { + 'ids': 'query', + 'namespace': 'query', + }, + 'collection_format_map': { + 'ids': 'multi', + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__fetch ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method update" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["update_request"] is not None: - _body_params = _params["update_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "object", - } - - return self.api_client.call_api( - "/vectors/update", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __query( + self, + query_request, + **kwargs + ): + """Query # noqa: E501 + + 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.query(query_request, async_req=True) + >>> result = thread.get() + + Args: + query_request (QueryRequest): + + 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: + QueryResponse + 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['query_request'] = \ + query_request + return self.call_with_http_info(**kwargs) + + self.query = _Endpoint( + settings={ + 'response_type': (QueryResponse,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/query', + 'operation_id': 'query', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'query_request', + ], + 'required': [ + 'query_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'query_request': + (QueryRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'query_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__query ) - @validate_arguments - def upsert(self, upsert_request: UpsertRequest, **kwargs) -> UpsertResponse: # noqa: E501 - """Upsert # noqa: E501 - - 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. # 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(upsert_request, async_req=True) - >>> result = thread.get() - - :param upsert_request: (required) - :type upsert_request: UpsertRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: 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. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: UpsertResponse - """ - kwargs["_return_http_data_only"] = True - if "_preload_content" in kwargs: - message = "Error! Please call the upsert_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.upsert_with_http_info(upsert_request, **kwargs) # noqa: E501 - - @validate_arguments - def upsert_with_http_info(self, upsert_request: UpsertRequest, **kwargs) -> ApiResponse: # noqa: E501 - """Upsert # noqa: E501 - - 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. # 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_with_http_info(upsert_request, async_req=True) - >>> result = thread.get() - - :param upsert_request: (required) - :type upsert_request: UpsertRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(UpsertResponse, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = ["upsert_request"] - _all_params.extend( - [ - "async_req", - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_request_auth", - "_content_type", - "_headers", - ] + def __update( + self, + update_request, + **kwargs + ): + """Update # noqa: E501 + + The `Update` operation updates 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. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update(update_request, async_req=True) + >>> result = thread.get() + + Args: + update_request (UpdateRequest): + + 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: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + 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['update_request'] = \ + update_request + return self.call_with_http_info(**kwargs) + + self.update = _Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/vectors/update', + 'operation_id': 'update', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'update_request', + ], + 'required': [ + 'update_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'update_request': + (UpdateRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'update_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__update ) - # validate the arguments - for _key, _val in _params["kwargs"].items(): - if _key not in _all_params: - raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method upsert" % _key) - _params[_key] = _val - del _params["kwargs"] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get("_headers", {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - if _params["upsert_request"] is not None: - _body_params = _params["upsert_request"] - - # set the HTTP header `Accept` - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) # noqa: E501 - - # set the HTTP header `Content-Type` - _content_types_list = _params.get( - "_content_type", self.api_client.select_header_content_type(["application/json"]) - ) - if _content_types_list: - _header_params["Content-Type"] = _content_types_list - - # authentication setting - _auth_settings = ["ApiKeyAuth"] # noqa: E501 - - _response_types_map = { - "200": "UpsertResponse", - } - - return self.api_client.call_api( - "/vectors/upsert", - "POST", - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get("async_req"), - _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 - _preload_content=_params.get("_preload_content", True), - _request_timeout=_params.get("_request_timeout"), - collection_formats=_collection_formats, - _request_auth=_params.get("_request_auth"), + def __upsert( + self, + upsert_request, + **kwargs + ): + """Upsert # noqa: E501 + + 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. # 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(upsert_request, async_req=True) + >>> result = thread.get() + + Args: + upsert_request (UpsertRequest): + + 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: + UpsertResponse + 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['upsert_request'] = \ + upsert_request + return self.call_with_http_info(**kwargs) + + self.upsert = _Endpoint( + settings={ + 'response_type': (UpsertResponse,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/vectors/upsert', + 'operation_id': 'upsert', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'upsert_request', + ], + 'required': [ + 'upsert_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'upsert_request': + (UpsertRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'upsert_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__upsert ) diff --git a/pinecone/core/client/api_client.py b/pinecone/core/client/api_client.py index 3c5bf896d..770fc07cd 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/client/api_client.py @@ -1,38 +1,46 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" -import atexit -import datetime -from dateutil.parser import parse import json +import atexit import mimetypes from multiprocessing.pool import ThreadPool +import io import os import re -import tempfile - +import typing from urllib.parse import quote - -from pinecone.core.client.configuration import Configuration -from pinecone.core.client.api_response import ApiResponse -import pinecone.core.client.models -from pinecone.core.client import rest -from pinecone.core.client.exceptions import ApiValueError, ApiException +from urllib3.fields import RequestField -class ApiClient: +from pinecone.core.client import rest +from pinecone.core.client.configuration import Configuration +from pinecone.core.client.exceptions import ApiTypeError, ApiValueError, ApiException +from pinecone.core.client.model_utils import ( + ModelNormal, + ModelSimple, + ModelComposed, + check_allowed_values, + check_validations, + date, + datetime, + deserialize_file, + file_type, + model_to_dict, + none_type, + validate_and_convert_types +) + + +class ApiClient(object): """Generic API client for OpenAPI client library builds. OpenAPI generic API client. This client handles the client- @@ -40,6 +48,10 @@ class ApiClient: the methods and models for each application are generated from the OpenAPI templates. + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to @@ -50,23 +62,12 @@ class ApiClient: to the API. More threads means more concurrent API requests. """ - PRIMITIVE_TYPES = (float, bool, bytes, str, int) - NATIVE_TYPES_MAPPING = { - "int": int, - "long": int, # TODO remove as only py3 is supported? - "float": float, - "str": str, - "bool": bool, - "date": datetime.date, - "datetime": datetime.datetime, - "object": object, - } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> None: - # use default configuration if none is provided + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): if configuration is None: - configuration = Configuration.get_default() + configuration = Configuration.get_default_copy() self.configuration = configuration self.pool_threads = pool_threads @@ -76,8 +77,7 @@ def __init__(self, configuration=None, header_name=None, header_value=None, cook self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. - self.user_agent = "OpenAPI-Generator/1.0.0/python" - self.client_side_validation = configuration.client_side_validation + self.user_agent = 'OpenAPI-Generator/1.0.0/python' def __enter__(self): return self @@ -90,13 +90,13 @@ def close(self): self._pool.close() self._pool.join() self._pool = None - if hasattr(atexit, "unregister"): + if hasattr(atexit, 'unregister'): atexit.unregister(self.close) @property def pool(self): """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. + avoids instantiating unused threadpool for blocking clients. """ if self._pool is None: atexit.register(self.close) @@ -106,95 +106,84 @@ def pool(self): @property def user_agent(self): """User agent for this API client""" - return self.default_headers["User-Agent"] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.default_headers["User-Agent"] = value + self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - _default = None - - @classmethod - def get_default(cls): - """Return new instance of ApiClient. - - This method returns newly created, based on default constructor, - object of ApiClient class or returns a copy of default - ApiClient. - - :return: The ApiClient object. - """ - if cls._default is None: - cls._default = ApiClient() - return cls._default - - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. - - It stores default ApiClient. - - :param default: object of ApiClient. - """ - cls._default = default - def __call_api( self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_types_map=None, - auth_settings=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - _host=None, - _request_auth=None, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None ): + config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: - header_params["Cookie"] = self.cookie + header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, collection_formats) + path_params = self.parameters_to_tuples(path_params, + collection_formats) for k, v in path_params: # specified safe chars, encode everything - resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)) + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) + post_params = self.parameters_to_tuples(post_params, + collection_formats) post_params.extend(self.files_parameters(files)) - - # auth setting - self.update_params_for_auth( - header_params, query_params, auth_settings, resource_path, method, body, request_auth=_request_auth - ) + if header_params['Content-Type'].startswith("multipart"): + post_params = self.parameters_to_multipart(post_params, + (dict) ) # body if body: body = self.sanitize_for_serialization(body) + # auth setting + self.update_params_for_auth(header_params, query_params, + auth_settings, resource_path, method, body) + # request url if _host is None: url = self.configuration.host + resource_path @@ -202,70 +191,73 @@ def __call_api( # use server/host defined in path or operation instead url = _host + resource_path - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, collection_formats) - url += "?" + url_query - try: # perform request and return response response_data = self.request( - method, - url, - query_params=query_params, - headers=header_params, - post_params=post_params, - body=body, + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) + _request_timeout=_request_timeout) except ApiException as e: - if e.body: - e.body = e.body.decode("utf-8") + e.body = e.body.decode('utf-8') raise e self.last_response = response_data - return_data = None # assuming derialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + return_data = response_data - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader("content-type") + if not _preload_content: + return (return_data) + return return_data + + # deserialize response data + if response_type: + if response_type != (file_type,): + encoding = "utf-8" + content_type = response_data.getheader('content-type') if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + if match: + encoding = match.group(1) response_data.data = response_data.data.decode(encoding) - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None + return_data = self.deserialize( + response_data, + response_type, + _check_type + ) + else: + return_data = None if _return_http_data_only: - return return_data + return (return_data) else: - return ApiResponse( - status_code=response_data.status, - data=return_data, - headers=response_data.getheaders(), - raw_data=response_data.data, - ) + return (return_data, response_data.status, + response_data.getheaders()) - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. + def parameters_to_multipart(self, params, collection_types): + """Get parameters as list of tuples, formatting as json if value is collection_types + :param params: Parameters as list of two-tuples + :param dict collection_types: Parameter collection types + :return: Parameters as list of tuple or urllib3.fields.RequestField + """ + new_params = [] + if collection_types is None: + collection_types = (dict) + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json + v = json.dumps(v, ensure_ascii=False).encode("utf-8") + field = RequestField(k, v) + field.make_multipart(content_type="application/json; charset=utf-8") + new_params.append(field) + else: + new_params.append((k, v)) + return new_params + + @classmethod + def sanitize_for_serialization(cls, obj): + """Prepares data for transmission before it is sent with the rest client If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date @@ -273,111 +265,92 @@ def sanitize_for_serialization(self, obj): If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. - + If obj is io.IOBase, return the bytes :param obj: The data to serialize. :return: The serialized form of data. """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): + if isinstance(obj, (ModelNormal, ModelComposed)): + return { + key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items() + } + elif isinstance(obj, io.IOBase): + return cls.get_file_data_and_close_file(obj) + elif isinstance(obj, (str, int, float, none_type, bool)): return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): + elif isinstance(obj, (datetime, date)): return obj.isoformat() - + elif isinstance(obj, ModelSimple): + return cls.sanitize_for_serialization(obj.value) + elif isinstance(obj, (list, tuple)): + return [cls.sanitize_for_serialization(item) for item in obj] if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = obj.to_dict() + return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} + raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) - return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()} - - def deserialize(self, response, response_type): + def deserialize(self, response, response_type, _check_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param _check_type: boolean, whether to check the types of the data + received from the server + :type _check_type: bool :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) + if response_type == (file_type,): + content_disposition = response.getheader("Content-Disposition") + return deserialize_file(response.data, self.configuration, + content_disposition=content_disposition) # fetch data from response object try: - data = json.loads(response.data) + received_data = json.loads(response.data) except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if isinstance(klass, str): - if klass.startswith("List["): - sub_kls = re.match(r"List\[(.*)]", klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - - if klass.startswith("Dict["): - sub_kls = re.match(r"Dict\[([^,]*), (.*)]", klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(pinecone.core.client.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) + received_data = response.data + + # store our data under the key of 'received_data' so users have some + # context if they are deserializing a string and the data type is wrong + deserialized_data = validate_and_convert_types( + received_data, + response_type, + ['received_data'], + True, + _check_type, + configuration=self.configuration + ) + return deserialized_data def call_api( self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_types_map=None, - auth_settings=None, - async_req=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - _host=None, - _request_auth=None, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + async_req: typing.Optional[bool] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None ): """Makes the HTTP request (synchronous) and returns deserialized data. @@ -393,26 +366,38 @@ def call_api( :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param files: key -> field name, value -> a list of open file + objects for `multipart/form-data`. + :type files: dict :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code + and headers + :type _return_http_data_only: bool, optional :param collection_formats: dict of collection formats for path, query, header, and post parameters. + :type collection_formats: dict, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional :param _request_timeout: 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. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional + :param _check_type: boolean describing if the data back from the server + should have its type checked. + :type _check_type: bool, optional :return: If async_req parameter is True, the request will be called asynchronously. @@ -421,124 +406,87 @@ def call_api( then the method will return the response directly. """ if not async_req: - return self.__call_api( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - - return self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ), - ) - - def request( - self, - method, - url, - query_params=None, - headers=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _check_type) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _check_type)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): """Makes the HTTP request using RESTClient.""" if method == "GET": - return self.rest_client.get_request( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) + return self.rest_client.GET(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) elif method == "HEAD": - return self.rest_client.head_request( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) + return self.rest_client.HEAD(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) elif method == "OPTIONS": - return self.rest_client.options_request( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) elif method == "POST": - return self.rest_client.post_request( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) elif method == "PUT": - return self.rest_client.put_request( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) elif method == "PATCH": - return self.rest_client.patch_request( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) elif method == "DELETE": - return self.rest_client.delete_request( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) else: - raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`.") + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -553,78 +501,59 @@ def parameters_to_tuples(self, params, collection_formats): for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] - if collection_format == "multi": + if collection_format == 'multi': new_params.extend((k, value) for value in v) else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' else: # csv is the default - delimiter = "," - new_params.append((k, delimiter.join(str(value) for value in v))) + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params - def parameters_to_url_query(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. + @staticmethod + def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: + file_data = file_instance.read() + file_instance.close() + return file_data - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: URL query string (e.g. a=Hello%20World&b=123) - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) - if isinstance(v, bool): - v = str(v).lower() - if isinstance(v, dict): - v = json.dumps(v) - - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == "multi": - new_params.extend((k, value) for value in v) - else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - new_params.append((k, delimiter.join(quote(str(value)) for value in v))) - else: - new_params.append((k, quote(str(v)))) - - return "&".join(["=".join(item) for item in new_params]) - - def files_parameters(self, files=None): + def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None): """Builds form parameters. - :param files: File parameters. - :return: Form parameters with files. + :param files: None or a dict with key=param_name and + value is a list of open file objects + :return: List of tuples of form parameters with file data """ - params = [] + if files is None: + return [] - if files: - for k, v in files.items(): - if not v: + params = [] + for param_name, file_instances in files.items(): + if file_instances is None: + # if the file field is nullable, skip None values + continue + for file_instance in file_instances: + if file_instance is None: + # if the file field is nullable, skip None values continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, "rb") as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + if file_instance.closed is True: + raise ApiValueError( + "Cannot read a closed file. The passed in file_type " + "for %s must be open." % param_name + ) + filename = os.path.basename(file_instance.name) + filedata = self.get_file_data_and_close_file(file_instance) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([param_name, tuple([filename, filedata, mimetype])])) return params @@ -637,11 +566,12 @@ def select_header_accept(self, accepts): if not accepts: return - for accept in accepts: - if re.search("json", accept, re.IGNORECASE): - return accept + accepts = [x.lower() for x in accepts] - return accepts[0] + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) def select_header_content_type(self, content_types): """Returns `Content-Type` based on an array of content_types provided. @@ -650,139 +580,271 @@ def select_header_content_type(self, content_types): :return: Content-Type (e.g. application/json). """ if not content_types: - return None + return 'application/json' - for content_type in content_types: - if re.search("json", content_type, re.IGNORECASE): - return content_type + content_types = [x.lower() for x in content_types] - return content_types[0] + if 'application/json' in content_types or '*/*' in content_types: + return 'application/json' + else: + return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, resource_path, method, body, request_auth=None): + def update_params_for_auth(self, headers, querys, auth_settings, + resource_path, method, body): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param request_auth: if set, the provided settings will - override the token in the configuration. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of _encoder.default(). """ if not auth_settings: return - if request_auth: - self._apply_auth_params(headers, queries, resource_path, method, body, request_auth) - return - for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) if auth_setting: - self._apply_auth_params(headers, queries, resource_path, method, body, auth_setting) - - def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): - """Updates the request parameters based on a single auth_setting - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param auth_setting: auth settings for the endpoint - """ - if auth_setting["in"] == "cookie": - headers["Cookie"] = auth_setting["value"] - elif auth_setting["in"] == "header": - if auth_setting["type"] != "http-signature": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - queries.append((auth_setting["key"], auth_setting["value"])) - else: - raise ApiValueError("Authentication token must be in `query` or `header`") - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + +class Endpoint(object): + def __init__(self, settings=None, params_map=None, root_map=None, + headers_map=None, api_client=None, callable=None): + """Creates an endpoint + + Args: + settings (dict): see below key value pairs + 'response_type' (tuple/None): response type + 'auth' (list): a list of auth type keys + 'endpoint_path' (str): the endpoint path + 'operation_id' (str): endpoint string identifier + 'http_method' (str): POST/PUT/PATCH/GET etc + 'servers' (list): list of str servers that this endpoint is at + params_map (dict): see below key value pairs + 'all' (list): list of str endpoint parameter names + 'required' (list): list of required parameter names + 'nullable' (list): list of nullable parameter names + 'enum' (list): list of parameters with enum values + 'validation' (list): list of parameters with validations + root_map + 'validations' (dict): the dict mapping endpoint parameter tuple + paths to their validation dictionaries + 'allowed_values' (dict): the dict mapping endpoint parameter + tuple paths to their allowed_values (enum) dictionaries + 'openapi_types' (dict): param_name to openapi type + 'attribute_map' (dict): param_name to camelCase name + 'location_map' (dict): param_name to 'body', 'file', 'form', + 'header', 'path', 'query' + collection_format_map (dict): param_name to `csv` etc. + headers_map (dict): see below key value pairs + 'accept' (list): list of Accept header strings + 'content_type' (list): list of Content-Type header strings + api_client (ApiClient) api client instance + callable (function): the function which is invoked when the + Endpoint is called """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. + self.settings = settings + self.params_map = params_map + self.params_map['all'].extend([ + 'async_req', + '_host_index', + '_preload_content', + '_request_timeout', + '_return_http_data_only', + '_check_input_type', + '_check_return_type' + ]) + self.params_map['nullable'].extend(['_request_timeout']) + self.validations = root_map['validations'] + self.allowed_values = root_map['allowed_values'] + self.openapi_types = root_map['openapi_types'] + extra_types = { + 'async_req': (bool,), + '_host_index': (none_type, int), + '_preload_content': (bool,), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), + '_return_http_data_only': (bool,), + '_check_input_type': (bool,), + '_check_return_type': (bool,) + } + self.openapi_types.update(extra_types) + self.attribute_map = root_map['attribute_map'] + self.location_map = root_map['location_map'] + self.collection_format_map = root_map['collection_format_map'] + self.headers_map = headers_map + self.api_client = api_client + self.callable = callable + + def __validate_inputs(self, kwargs): + for param in self.params_map['enum']: + if param in kwargs: + check_allowed_values( + self.allowed_values, + (param,), + kwargs[param] + ) + + for param in self.params_map['validation']: + if param in kwargs: + check_validations( + self.validations, + (param,), + kwargs[param], + configuration=self.api_client.configuration + ) + + if kwargs['_check_input_type'] is False: + return - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data + for key, value in kwargs.items(): + fixed_val = validate_and_convert_types( + value, + self.openapi_types[key], + [key], + False, + kwargs['_check_input_type'], + configuration=self.api_client.configuration + ) + kwargs[key] = fixed_val + + def __gather_params(self, kwargs): + params = { + 'body': None, + 'collection_format': {}, + 'file': {}, + 'form': [], + 'header': {}, + 'path': {}, + 'query': [] + } + + for param_name, param_value in kwargs.items(): + param_location = self.location_map.get(param_name) + if param_location is None: + continue + if param_location: + if param_location == 'body': + params['body'] = param_value + continue + base_name = self.attribute_map[param_name] + if (param_location == 'form' and + self.openapi_types[param_name] == (file_type,)): + params['file'][param_name] = [param_value] + elif (param_location == 'form' and + self.openapi_types[param_name] == ([file_type],)): + # param_value is already a list + params['file'][param_name] = param_value + elif param_location in {'form', 'query'}: + param_value_full = (base_name, param_value) + params[param_location].append(param_value_full) + if param_location not in {'form', 'query'}: + params[param_location][base_name] = param_value + collection_format = self.collection_format_map.get(param_name) + if collection_format: + params['collection_format'][base_name] = collection_format - def __deserialize_object(self, value): - """Return an original value. + return params - :return: object. - """ - return value + def __call__(self, *args, **kwargs): + """ This method is invoked when endpoints are called + Example: - def __deserialize_date(self, string): - """Deserializes string to date. + api_instance = IndexOperationsApi() + api_instance.configure_index # this is an instance of the class Endpoint + api_instance.configure_index() # this invokes api_instance.configure_index.__call__() + which then invokes the callable functions stored in that endpoint at + api_instance.configure_index.callable or self.callable in this class - :param string: str. - :return: date. """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string)) + return self.callable(self, *args, **kwargs) - def __deserialize_datetime(self, string): - """Deserializes string to datetime. + def call_with_http_info(self, **kwargs): - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string))) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - return klass.from_dict(data) + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) + except IndexError: + if self.settings['servers']: + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" % + len(self.settings['servers']) + ) + _host = None + + for key, value in kwargs.items(): + if key not in self.params_map['all']: + raise ApiTypeError( + "Got an unexpected parameter '%s'" + " to method `%s`" % + (key, self.settings['operation_id']) + ) + # only throw this nullable ApiValueError if _check_input_type + # is False, if _check_input_type==True we catch this case + # in self.__validate_inputs + if (key not in self.params_map['nullable'] and value is None + and kwargs['_check_input_type'] is False): + raise ApiValueError( + "Value may not be None for non-nullable parameter `%s`" + " when calling `%s`" % + (key, self.settings['operation_id']) + ) + + for key in self.params_map['required']: + if key not in kwargs.keys(): + raise ApiValueError( + "Missing the required parameter `%s` when calling " + "`%s`" % (key, self.settings['operation_id']) + ) + + self.__validate_inputs(kwargs) + + params = self.__gather_params(kwargs) + + accept_headers_list = self.headers_map['accept'] + if accept_headers_list: + params['header']['Accept'] = self.api_client.select_header_accept( + accept_headers_list) + + content_type_headers_list = self.headers_map['content_type'] + if content_type_headers_list: + header_list = self.api_client.select_header_content_type( + content_type_headers_list) + params['header']['Content-Type'] = header_list + + return self.api_client.call_api( + self.settings['endpoint_path'], self.settings['http_method'], + params['path'], + params['query'], + params['header'], + body=params['body'], + post_params=params['form'], + files=params['file'], + response_type=self.settings['response_type'], + auth_settings=self.settings['auth'], + async_req=kwargs['async_req'], + _check_type=kwargs['_check_return_type'], + _return_http_data_only=kwargs['_return_http_data_only'], + _preload_content=kwargs['_preload_content'], + _request_timeout=kwargs['_request_timeout'], + _host=_host, + collection_formats=params['collection_format']) diff --git a/pinecone/core/client/api_response.py b/pinecone/core/client/api_response.py deleted file mode 100644 index 7bc03cb63..000000000 --- a/pinecone/core/client/api_response.py +++ /dev/null @@ -1,22 +0,0 @@ -"""API response object.""" - -from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr - - -class ApiResponse: - """ - API response object - """ - - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") - - def __init__(self, status_code=None, headers=None, data=None, raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data diff --git a/pinecone/core/client/apis/__init__.py b/pinecone/core/client/apis/__init__.py new file mode 100644 index 000000000..ec42b1a85 --- /dev/null +++ b/pinecone/core/client/apis/__init__.py @@ -0,0 +1,18 @@ + +# flake8: noqa + +# Import all APIs into this package. +# If you have many APIs here with many many models used in each API this may +# raise a `RecursionError`. +# In order to avoid this, import only the API that you directly need like: +# +# from .api.index_operations_api import IndexOperationsApi +# +# or import this package, but before doing it, use: +# +# import sys +# sys.setrecursionlimit(n) + +# Import APIs into API package: +from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/client/configuration.py b/pinecone/core/client/configuration.py index 7ebb57e54..6e2d4949b 100644 --- a/pinecone/core/client/configuration.py +++ b/pinecone/core/client/configuration.py @@ -1,16 +1,12 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" import copy @@ -19,88 +15,104 @@ import sys import urllib3 -import http.client as httplib +from http import client as http_client +from pinecone.core.client.exceptions import ApiValueError + JSON_SCHEMA_VALIDATION_KEYWORDS = { - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "maxItems", - "minItems", + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' } +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. -class Configuration: - """This class contains various settings of the API client. - - :param host: Base url. - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer). - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication. - :param password: Password for HTTP basic authentication. - :param access_token: Access token. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum - values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format. - - :Example: - - API Key Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - cookieAuth: # name for the security scheme - type: apiKey - in: cookie - name: JSESSIONID # cookie name - - You can programmatically set the cookie: - - conf = pinecone.core.client.Configuration( - api_key={'cookieAuth': 'abc123'} - api_key_prefix={'cookieAuth': 'JSESSIONID'} - ) - - The following cookie will be added to the HTTP request: - Cookie: JSESSIONID abc123 + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = pinecone.core.client.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 """ _default = None - def __init__( - self, - host=None, - api_key=None, - api_key_prefix=None, - username=None, - password=None, - access_token=None, - server_index=None, - server_variables=None, - server_operation_index=None, - server_operation_variables=None, - ssl_ca_cert=None, - ) -> None: - """Constructor""" + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + access_token=None, + username=None, password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor + """ self._base_path = "https://unknown-unknown.svc.unknown.pinecone.io" if host is None else host """Default Base url """ @@ -116,6 +128,7 @@ def __init__( """Temp file folder for downloading files """ # Authentication Settings + self.access_token = access_token self.api_key = {} if api_key: self.api_key = api_key @@ -135,15 +148,14 @@ def __init__( self.password = password """Password for HTTP basic authentication """ - self.access_token = access_token - """Access token - """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations self.logger = {} """Logging Settings """ self.logger["package_logger"] = logging.getLogger("pinecone.core.client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = "%(asctime)s %(levelname)s %(message)s" + self.logger_format = '%(asctime)s %(levelname)s %(message)s' """Log format """ self.logger_stream_handler = None @@ -176,10 +188,6 @@ def __init__( self.assert_hostname = None """Set this to True/False to enable/disable SSL hostname verification. """ - self.tls_server_name = None - """SSL/TLS Server Name Indication (SNI) - Set this to the SNI value expected by the server. - """ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 """urllib3 connection pool's maximum number of connections saved @@ -195,7 +203,7 @@ def __init__( self.proxy_headers = None """Proxy headers """ - self.safe_chars_for_path_param = "" + self.safe_chars_for_path_param = '' """Safe chars for path_param """ self.retries = None @@ -204,24 +212,15 @@ def __init__( # Enable client side validation self.client_side_validation = True + # Options to pass down to the underlying urllib3 socket self.socket_options = None - """Options to pass down to the underlying urllib3 socket - """ - - self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" - """datetime format - """ - - self.date_format = "%Y-%m-%d" - """date format - """ def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): - if k not in ("logger", "logger_file_handler"): + if k not in ('logger', 'logger_file_handler'): setattr(result, k, copy.deepcopy(v, memo)) # shallow copy of loggers result.logger = copy.copy(self.logger) @@ -232,6 +231,13 @@ def __deepcopy__(self, memo): def __setattr__(self, name, value): object.__setattr__(self, name, value) + if name == 'disabled_client_side_validations': + s = set(filter(None, value.split(','))) + for v in s: + if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: + raise ApiValueError( + "Invalid keyword: '{0}''".format(v)) + self._disabled_client_side_validations = s @classmethod def set_default(cls, default): @@ -242,31 +248,21 @@ def set_default(cls, default): :param default: object of Configuration """ - cls._default = default + cls._default = copy.deepcopy(default) @classmethod def get_default_copy(cls): - """Deprecated. Please use `get_default` instead. - - Deprecated. Please use `get_default` instead. - - :return: The configuration object. - """ - return cls.get_default() - - @classmethod - def get_default(cls): - """Return the default configuration. + """Return new instance of configuration. This method returns newly created, based on default constructor, object of Configuration class or returns a copy of default - configuration. + configuration passed by the set_default method. :return: The configuration object. """ - if cls._default is None: - cls._default = Configuration() - return cls._default + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() @property def logger_file(self): @@ -320,15 +316,15 @@ def debug(self, value): # if debug status is True, turn on debug logging for _, logger in self.logger.items(): logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 + # turn on http_client debug + http_client.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` for _, logger in self.logger.items(): logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 + # turn off http_client debug + http_client.HTTPConnection.debuglevel = 0 @property def logger_format(self): @@ -381,7 +377,9 @@ def get_basic_auth_token(self): password = "" if self.password is not None: password = self.password - return urllib3.util.make_headers(basic_auth=username + ":" + password).get("authorization") + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') def auth_settings(self): """Gets Auth Settings dict for api client. @@ -389,13 +387,13 @@ def auth_settings(self): :return: The Auth Settings information dict. """ auth = {} - if "ApiKeyAuth" in self.api_key: - auth["ApiKeyAuth"] = { - "type": "api_key", - "in": "header", - "key": "Api-Key", - "value": self.get_api_key_with_prefix( - "ApiKeyAuth", + if 'ApiKeyAuth' in self.api_key: + auth['ApiKeyAuth'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'Api-Key', + 'value': self.get_api_key_with_prefix( + 'ApiKeyAuth', ), } return auth @@ -405,13 +403,12 @@ def to_debug_report(self): :return: The report for debugging. """ - return ( - "Python SDK Debug Report:\n" - "OS: {env}\n" - "Python Version: {pyversion}\n" - "Version of the API: version not set\n" - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - ) + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: version not set\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) def get_host_settings(self): """Gets an array of host settings @@ -420,22 +417,22 @@ def get_host_settings(self): """ return [ { - "url": "https://{index_name}-{project_name}.svc.{environment}.pinecone.io", - "description": "No description provided", - "variables": { - "index_name": { - "description": "No description provided", - "default_value": "unknown", - }, - "project_name": { - "description": "No description provided", - "default_value": "unknown", - }, - "environment": { - "description": "No description provided", - "default_value": "unknown", - }, - }, + 'url': "https://{index_name}-{project_name}.svc.{environment}.pinecone.io", + 'description': "No description provided", + 'variables': { + 'index_name': { + 'description': "No description provided", + 'default_value': "unknown", + }, + 'project_name': { + 'description': "No description provided", + 'default_value': "unknown", + }, + 'environment': { + 'description': "No description provided", + 'default_value': "unknown", + } + } } ] @@ -457,20 +454,22 @@ def get_host_from_settings(self, index, variables=None, servers=None): except IndexError: raise ValueError( "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers)) - ) + "Must be less than {1}".format(index, len(servers))) - url = server["url"] + url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server.get("variables", {}).items(): - used_value = variables.get(variable_name, variable["default_value"]) + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) - if "enum_values" in variable and used_value not in variable["enum_values"]: + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: raise ValueError( "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format(variable_name, variables[variable_name], variable["enum_values"]) - ) + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) url = url.replace("{" + variable_name + "}", used_value) diff --git a/pinecone/core/client/exceptions.py b/pinecone/core/client/exceptions.py index 7a26ac073..dd777d024 100644 --- a/pinecone/core/client/exceptions.py +++ b/pinecone/core/client/exceptions.py @@ -1,16 +1,13 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) + Generated by: https://openapi-generator.tech +""" - Do not edit the class manually. -""" # noqa: E501 class OpenApiException(Exception): @@ -18,8 +15,9 @@ class OpenApiException(Exception): class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> None: - """Raises an exception for TypeErrors + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors Args: msg (str): the exception message @@ -46,7 +44,7 @@ def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None) -> None: + def __init__(self, msg, path_to_item=None): """ Args: msg (str): the exception message @@ -64,7 +62,7 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None) -> None: + def __init__(self, msg, path_to_item=None): """ Raised when an attribute reference or assignment fails. @@ -83,7 +81,7 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None) -> None: + def __init__(self, msg, path_to_item=None): """ Args: msg (str): the exception message @@ -100,7 +98,8 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + + def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status self.reason = http_resp.reason @@ -114,9 +113,11 @@ def __init__(self, status=None, reason=None, http_resp=None) -> None: def __str__(self): """Custom error messages for exception""" - error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason) + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) @@ -124,28 +125,27 @@ def __str__(self): return error_message -class BadRequestException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) - - class NotFoundException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + + def __init__(self, status=None, reason=None, http_resp=None): super(NotFoundException, self).__init__(status, reason, http_resp) class UnauthorizedException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + + def __init__(self, status=None, reason=None, http_resp=None): super(UnauthorizedException, self).__init__(status, reason, http_resp) class ForbiddenException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + + def __init__(self, status=None, reason=None, http_resp=None): super(ForbiddenException, self).__init__(status, reason, http_resp) class ServiceException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + + def __init__(self, status=None, reason=None, http_resp=None): super(ServiceException, self).__init__(status, reason, http_resp) diff --git a/pinecone/core/client/model/__init__.py b/pinecone/core/client/model/__init__.py new file mode 100644 index 000000000..cfe32b784 --- /dev/null +++ b/pinecone/core/client/model/__init__.py @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from {{packageName}.models import ModelA, ModelB diff --git a/pinecone/core/client/model/approximated_config.py b/pinecone/core/client/model/approximated_config.py new file mode 100644 index 000000000..9e881a945 --- /dev/null +++ b/pinecone/core/client/model/approximated_config.py @@ -0,0 +1,260 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class ApproximatedConfig(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'k_bits': (int,), # noqa: E501 + 'hybrid': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'k_bits': 'k_bits', # noqa: E501 + 'hybrid': 'hybrid', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApproximatedConfig - 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,) + k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 + hybrid (bool): [optional] if omitted the server will use the default value of False # 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 ApiTypeError( + "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 + """ApproximatedConfig - 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,) + k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 + hybrid (bool): [optional] if omitted the server will use the default value of False # 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 ApiTypeError( + "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 ApiAttributeError(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/client/model/collection_meta.py b/pinecone/core/client/model/collection_meta.py new file mode 100644 index 000000000..cc3bfa5f1 --- /dev/null +++ b/pinecone/core/client/model/collection_meta.py @@ -0,0 +1,272 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class CollectionMeta(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'size': (int,), # noqa: E501 + 'status': (str,), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'vector_count': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'size': 'size', # noqa: E501 + 'status': 'status', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'vector_count': 'vector_count', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CollectionMeta - 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,) + name (str): [optional] # noqa: E501 + size (int): The size of the collection in bytes.. [optional] # noqa: E501 + status (str): The status of the collection.. [optional] # noqa: E501 + dimension (int): [optional] # noqa: E501 + vector_count (int): [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 ApiTypeError( + "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 + """CollectionMeta - 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,) + name (str): [optional] # noqa: E501 + size (int): The size of the collection in bytes.. [optional] # noqa: E501 + status (str): The status of the collection.. [optional] # noqa: E501 + dimension (int): [optional] # noqa: E501 + vector_count (int): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/create_collection_request.py b/pinecone/core/client/model/create_collection_request.py new file mode 100644 index 000000000..ac5474413 --- /dev/null +++ b/pinecone/core/client/model/create_collection_request.py @@ -0,0 +1,268 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class CreateCollectionRequest(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'source': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'source': 'source', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, source, *args, **kwargs): # noqa: E501 + """CreateCollectionRequest - a model defined in OpenAPI + + Args: + name (str): The name of the collection to be created. + source (str): The name of the source index to be used as the source for the collection. + + 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 ApiTypeError( + "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.source = source + 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, source, *args, **kwargs): # noqa: E501 + """CreateCollectionRequest - a model defined in OpenAPI + + Args: + name (str): The name of the collection to be created. + source (str): The name of the source index to be used as the source for the collection. + + 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 ApiTypeError( + "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.source = source + 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 ApiAttributeError(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/client/model/create_request.py b/pinecone/core/client/model/create_request.py new file mode 100644 index 000000000..0dbb9f900 --- /dev/null +++ b/pinecone/core/client/model/create_request.py @@ -0,0 +1,304 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class CreateRequest(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'index_type': (str,), # noqa: E501 + 'metric': (str,), # noqa: E501 + 'pods': (int,), # noqa: E501 + 'replicas': (int,), # noqa: E501 + 'shards': (int,), # noqa: E501 + 'pod_type': (str,), # noqa: E501 + 'index_config': (dict,), # noqa: E501 + 'metadata_config': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 + 'source_collection': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'index_type': 'index_type', # noqa: E501 + 'metric': 'metric', # noqa: E501 + 'pods': 'pods', # noqa: E501 + 'replicas': 'replicas', # noqa: E501 + 'shards': 'shards', # noqa: E501 + 'pod_type': 'pod_type', # noqa: E501 + 'index_config': 'index_config', # noqa: E501 + 'metadata_config': 'metadata_config', # noqa: E501 + 'source_collection': 'source_collection', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 + """CreateRequest - a model defined in OpenAPI + + Args: + name (str): The name of the index to be created. The maximum length is 45 characters. + dimension (int): The dimensions of the vectors to be inserted in 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,) + index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 + 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 + pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 + index_config (dict): [optional] # noqa: E501 + metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 + source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( + "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.dimension = dimension + 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, dimension, *args, **kwargs): # noqa: E501 + """CreateRequest - a model defined in OpenAPI + + Args: + name (str): The name of the index to be created. The maximum length is 45 characters. + dimension (int): The dimensions of the vectors to be inserted in 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,) + index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 + 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 + pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 + index_config (dict): [optional] # noqa: E501 + metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 + source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( + "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.dimension = dimension + 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 ApiAttributeError(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/client/model/delete_request.py b/pinecone/core/client/model/delete_request.py new file mode 100644 index 000000000..446466d57 --- /dev/null +++ b/pinecone/core/client/model/delete_request.py @@ -0,0 +1,270 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class DeleteRequest(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 = { + ('ids',): { + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'ids': ([str],), # noqa: E501 + 'delete_all': (bool,), # noqa: E501 + 'namespace': (str,), # noqa: E501 + 'filter': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'ids': 'ids', # noqa: E501 + 'delete_all': 'deleteAll', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + 'filter': 'filter', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DeleteRequest - 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,) + 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, date, datetime, 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 https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( + "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 + """DeleteRequest - 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,) + 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, date, datetime, 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 https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/describe_index_stats_request.py b/pinecone/core/client/model/describe_index_stats_request.py new file mode 100644 index 000000000..da0eb0b24 --- /dev/null +++ b/pinecone/core/client/model/describe_index_stats_request.py @@ -0,0 +1,256 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class DescribeIndexStatsRequest(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'filter': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'filter': 'filter', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DescribeIndexStatsRequest - 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,) + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( + "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 + """DescribeIndexStatsRequest - 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,) + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/describe_index_stats_response.py b/pinecone/core/client/model/describe_index_stats_response.py new file mode 100644 index 000000000..9dc9c4056 --- /dev/null +++ b/pinecone/core/client/model/describe_index_stats_response.py @@ -0,0 +1,274 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.namespace_summary import NamespaceSummary + globals()['NamespaceSummary'] = NamespaceSummary + + +class DescribeIndexStatsResponse(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'namespaces': ({str: (NamespaceSummary,)},), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'index_fullness': (float,), # noqa: E501 + 'total_vector_count': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'namespaces': 'namespaces', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'index_fullness': 'indexFullness', # noqa: E501 + 'total_vector_count': 'totalVectorCount', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DescribeIndexStatsResponse - 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,) + 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%.. [optional] # noqa: E501 + total_vector_count (int): [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 ApiTypeError( + "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 + """DescribeIndexStatsResponse - 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,) + 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%.. [optional] # noqa: E501 + total_vector_count (int): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/fetch_response.py b/pinecone/core/client/model/fetch_response.py new file mode 100644 index 000000000..d355980fc --- /dev/null +++ b/pinecone/core/client/model/fetch_response.py @@ -0,0 +1,266 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.vector import Vector + globals()['Vector'] = Vector + + +class FetchResponse(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'vectors': ({str: (Vector,)},), # noqa: E501 + 'namespace': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'vectors': 'vectors', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FetchResponse - 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,) + vectors ({str: (Vector,)}): [optional] # noqa: E501 + namespace (str): The namespace of the vectors.. [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 ApiTypeError( + "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 + """FetchResponse - 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,) + vectors ({str: (Vector,)}): [optional] # noqa: E501 + namespace (str): The namespace of the vectors.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/hnsw_config.py b/pinecone/core/client/model/hnsw_config.py new file mode 100644 index 000000000..d6a99a345 --- /dev/null +++ b/pinecone/core/client/model/hnsw_config.py @@ -0,0 +1,268 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class HnswConfig(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'ef_construction': (int,), # noqa: E501 + 'ef': (int,), # noqa: E501 + 'm': (int,), # noqa: E501 + 'max_elements': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'ef_construction': 'ef_construction', # noqa: E501 + 'ef': 'ef', # noqa: E501 + 'm': 'M', # noqa: E501 + 'max_elements': 'max_elements', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HnswConfig - 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,) + ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 + ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 + m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 + max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( + "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 + """HnswConfig - 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,) + ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 + ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 + m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 + max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( + "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 ApiAttributeError(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/client/model/index_meta.py b/pinecone/core/client/model/index_meta.py new file mode 100644 index 000000000..5f17947dd --- /dev/null +++ b/pinecone/core/client/model/index_meta.py @@ -0,0 +1,268 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.index_meta_database import IndexMetaDatabase + from pinecone.core.client.model.index_meta_status import IndexMetaStatus + globals()['IndexMetaDatabase'] = IndexMetaDatabase + globals()['IndexMetaStatus'] = IndexMetaStatus + + +class IndexMeta(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'database': (IndexMetaDatabase,), # noqa: E501 + 'status': (IndexMetaStatus,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'database': 'database', # noqa: E501 + 'status': 'status', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IndexMeta - 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,) + database (IndexMetaDatabase): [optional] # noqa: E501 + status (IndexMetaStatus): [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 ApiTypeError( + "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 + """IndexMeta - 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,) + database (IndexMetaDatabase): [optional] # noqa: E501 + status (IndexMetaStatus): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/index_meta_database.py b/pinecone/core/client/model/index_meta_database.py new file mode 100644 index 000000000..d93ddf057 --- /dev/null +++ b/pinecone/core/client/model/index_meta_database.py @@ -0,0 +1,292 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class IndexMetaDatabase(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'dimension': (str,), # noqa: E501 + 'index_type': (str,), # noqa: E501 + 'metric': (str,), # noqa: E501 + 'pods': (int,), # noqa: E501 + 'replicas': (int,), # noqa: E501 + 'shards': (int,), # noqa: E501 + 'pod_type': (str,), # noqa: E501 + 'index_config': (dict,), # noqa: E501 + 'metadata_config': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'index_type': 'index_type', # noqa: E501 + 'metric': 'metric', # noqa: E501 + 'pods': 'pods', # noqa: E501 + 'replicas': 'replicas', # noqa: E501 + 'shards': 'shards', # noqa: E501 + 'pod_type': 'pod_type', # noqa: E501 + 'index_config': 'index_config', # noqa: E501 + 'metadata_config': 'metadata_config', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IndexMetaDatabase - 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,) + name (str): [optional] # noqa: E501 + dimension (str): [optional] # noqa: E501 + index_type (str): [optional] # noqa: E501 + metric (str): [optional] # noqa: E501 + pods (int): [optional] # noqa: E501 + replicas (int): [optional] # noqa: E501 + shards (int): [optional] # noqa: E501 + pod_type (str): [optional] # noqa: E501 + index_config (dict): [optional] # noqa: E501 + metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [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 ApiTypeError( + "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 + """IndexMetaDatabase - 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,) + name (str): [optional] # noqa: E501 + dimension (str): [optional] # noqa: E501 + index_type (str): [optional] # noqa: E501 + metric (str): [optional] # noqa: E501 + pods (int): [optional] # noqa: E501 + replicas (int): [optional] # noqa: E501 + shards (int): [optional] # noqa: E501 + pod_type (str): [optional] # noqa: E501 + index_config (dict): [optional] # noqa: E501 + metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/index_meta_status.py b/pinecone/core/client/model/index_meta_status.py new file mode 100644 index 000000000..62abdbd66 --- /dev/null +++ b/pinecone/core/client/model/index_meta_status.py @@ -0,0 +1,278 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class IndexMetaStatus(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 = { + ('state',): { + 'INITIALIZING': "Initializing", + 'INITIALIZATIONFAILED': "InitializationFailed", + 'SCALINGUP': "ScalingUp", + 'SCALINGDOWN': "ScalingDown", + 'SCALINGUPPODSIZE': "ScalingUpPodSize", + 'SCALINGDOWNPODSIZE': "ScalingDownPodSize", + 'TERMINATING': "Terminating", + 'READY': "Ready", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'ready': (bool,), # noqa: E501 + 'state': (str,), # noqa: E501 + 'host': (str,), # noqa: E501 + 'port': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'ready': 'ready', # noqa: E501 + 'state': 'state', # noqa: E501 + 'host': 'host', # noqa: E501 + 'port': 'port', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IndexMetaStatus - 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,) + ready (bool): [optional] # noqa: E501 + state (str): [optional] # noqa: E501 + host (str): [optional] # noqa: E501 + port (int): [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 ApiTypeError( + "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 + """IndexMetaStatus - 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,) + ready (bool): [optional] # noqa: E501 + state (str): [optional] # noqa: E501 + host (str): [optional] # noqa: E501 + port (int): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/namespace_summary.py b/pinecone/core/client/model/namespace_summary.py new file mode 100644 index 000000000..33633f796 --- /dev/null +++ b/pinecone/core/client/model/namespace_summary.py @@ -0,0 +1,256 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class NamespaceSummary(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'vector_count': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'vector_count': 'vectorCount', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NamespaceSummary - 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,) + vector_count (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.. [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 ApiTypeError( + "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 + """NamespaceSummary - 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,) + vector_count (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.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/patch_request.py b/pinecone/core/client/model/patch_request.py new file mode 100644 index 000000000..53425c222 --- /dev/null +++ b/pinecone/core/client/model/patch_request.py @@ -0,0 +1,260 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class PatchRequest(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'replicas': (int,), # noqa: E501 + 'pod_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'replicas': 'replicas', # noqa: E501 + 'pod_type': 'pod_type', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """PatchRequest - 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,) + replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 + pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [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 ApiTypeError( + "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 + """PatchRequest - 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,) + replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 + pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/protobuf_any.py b/pinecone/core/client/model/protobuf_any.py new file mode 100644 index 000000000..365f5064c --- /dev/null +++ b/pinecone/core/client/model/protobuf_any.py @@ -0,0 +1,260 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class ProtobufAny(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'type_url': (str,), # noqa: E501 + 'value': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'type_url': 'typeUrl', # noqa: E501 + 'value': 'value', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ProtobufAny - 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,) + type_url (str): [optional] # noqa: E501 + value (str): [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 ApiTypeError( + "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 + """ProtobufAny - 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,) + type_url (str): [optional] # noqa: E501 + value (str): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/protobuf_null_value.py b/pinecone/core/client/model/protobuf_null_value.py new file mode 100644 index 000000000..63129117d --- /dev/null +++ b/pinecone/core/client/model/protobuf_null_value.py @@ -0,0 +1,280 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class ProtobufNullValue(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'NULL_VALUE': "NULL_VALUE", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """ProtobufNullValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + + Keyword Args: + value (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "NULL_VALUE" + + _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 ApiTypeError( + "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 ApiTypeError( + "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): + """ProtobufNullValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + + Keyword Args: + value (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "NULL_VALUE" + + _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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/query_request.py b/pinecone/core/client/model/query_request.py new file mode 100644 index 000000000..774d06f73 --- /dev/null +++ b/pinecone/core/client/model/query_request.py @@ -0,0 +1,313 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.query_vector import QueryVector + from pinecone.core.client.model.sparse_values import SparseValues + globals()['QueryVector'] = QueryVector + globals()['SparseValues'] = SparseValues + + +class QueryRequest(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 = { + ('top_k',): { + 'inclusive_maximum': 10000, + 'inclusive_minimum': 1, + }, + ('queries',): { + }, + ('vector',): { + }, + ('id',): { + 'max_length': 512, + }, + } + + @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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'top_k': (int,), # noqa: E501 + 'namespace': (str,), # noqa: E501 + 'filter': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'include_values': (bool,), # noqa: E501 + 'include_metadata': (bool,), # noqa: E501 + 'queries': ([QueryVector],), # noqa: E501 + 'vector': ([float],), # noqa: E501 + 'sparse_vector': (SparseValues,), # noqa: E501 + 'id': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'top_k': 'topK', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + 'filter': 'filter', # noqa: E501 + 'include_values': 'includeValues', # noqa: E501 + 'include_metadata': 'includeMetadata', # noqa: E501 + 'queries': 'queries', # noqa: E501 + 'vector': 'vector', # noqa: E501 + 'sparse_vector': 'sparseVector', # noqa: E501 + 'id': 'id', # 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 + """QueryRequest - a model defined in OpenAPI + + Args: + top_k (int): The number of results to return for each query. + + 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,) + namespace (str): The namespace to query.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [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 + vector ([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`.. [optional] # noqa: E501 + sparse_vector (SparseValues): [optional] # noqa: E501 + id (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`.. [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 ApiTypeError( + "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 + """QueryRequest - a model defined in OpenAPI + + Args: + top_k (int): The number of results to return for each query. + + 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,) + namespace (str): The namespace to query.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [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 + vector ([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`.. [optional] # noqa: E501 + sparse_vector (SparseValues): [optional] # noqa: E501 + id (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`.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/query_response.py b/pinecone/core/client/model/query_response.py new file mode 100644 index 000000000..886c93000 --- /dev/null +++ b/pinecone/core/client/model/query_response.py @@ -0,0 +1,272 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.scored_vector import ScoredVector + from pinecone.core.client.model.single_query_results import SingleQueryResults + globals()['ScoredVector'] = ScoredVector + globals()['SingleQueryResults'] = SingleQueryResults + + +class QueryResponse(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'results': ([SingleQueryResults],), # noqa: E501 + 'matches': ([ScoredVector],), # noqa: E501 + 'namespace': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'results': 'results', # noqa: E501 + 'matches': 'matches', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """QueryResponse - 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,) + results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 + matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 + namespace (str): The namespace for the vectors.. [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 ApiTypeError( + "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 + """QueryResponse - 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,) + results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 + matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 + namespace (str): The namespace for the vectors.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/query_vector.py b/pinecone/core/client/model/query_vector.py new file mode 100644 index 000000000..b7220d5d9 --- /dev/null +++ b/pinecone/core/client/model/query_vector.py @@ -0,0 +1,290 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.sparse_values import SparseValues + globals()['SparseValues'] = SparseValues + + +class QueryVector(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 = { + ('values',): { + }, + ('top_k',): { + 'inclusive_maximum': 10000, + '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 + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'values': ([float],), # noqa: E501 + 'sparse_values': (SparseValues,), # noqa: E501 + 'top_k': (int,), # noqa: E501 + 'namespace': (str,), # noqa: E501 + 'filter': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'values': 'values', # noqa: E501 + 'sparse_values': 'sparseValues', # noqa: E501 + 'top_k': 'topK', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + 'filter': 'filter', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, values, *args, **kwargs): # noqa: E501 + """QueryVector - a model defined in OpenAPI + + Args: + values ([float]): The query vector values. This should be the same length as the dimension of the index being queried. + + 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,) + sparse_values (SparseValues): [optional] # noqa: E501 + top_k (int): An override for the number of results to return for this query vector.. [optional] # noqa: E501 + namespace (str): An override the namespace to search.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): An override for the metadata filter to apply. This replaces the request-level filter.. [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 ApiTypeError( + "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.values = values + 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, values, *args, **kwargs): # noqa: E501 + """QueryVector - a model defined in OpenAPI + + Args: + values ([float]): The query vector values. This should be the same length as the dimension of the index being queried. + + 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,) + sparse_values (SparseValues): [optional] # noqa: E501 + top_k (int): An override for the number of results to return for this query vector.. [optional] # noqa: E501 + namespace (str): An override the namespace to search.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): An override for the metadata filter to apply. This replaces the request-level filter.. [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 ApiTypeError( + "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.values = values + 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 ApiAttributeError(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/client/model/rpc_status.py b/pinecone/core/client/model/rpc_status.py new file mode 100644 index 000000000..30ff15f95 --- /dev/null +++ b/pinecone/core/client/model/rpc_status.py @@ -0,0 +1,270 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.protobuf_any import ProtobufAny + globals()['ProtobufAny'] = ProtobufAny + + +class RpcStatus(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'code': (int,), # noqa: E501 + 'message': (str,), # noqa: E501 + 'details': ([ProtobufAny],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'code': 'code', # noqa: E501 + 'message': 'message', # noqa: E501 + 'details': 'details', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """RpcStatus - 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,) + code (int): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + details ([ProtobufAny]): [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 ApiTypeError( + "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 + """RpcStatus - 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,) + code (int): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + details ([ProtobufAny]): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/scored_vector.py b/pinecone/core/client/model/scored_vector.py new file mode 100644 index 000000000..88cd807db --- /dev/null +++ b/pinecone/core/client/model/scored_vector.py @@ -0,0 +1,288 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.sparse_values import SparseValues + globals()['SparseValues'] = SparseValues + + +class ScoredVector(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 = { + ('id',): { + 'max_length': 512, + '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'id': (str,), # noqa: E501 + 'score': (float,), # noqa: E501 + 'values': ([float],), # noqa: E501 + 'sparse_values': (SparseValues,), # noqa: E501 + 'metadata': ({str: (bool, date, datetime, 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 + 'values': 'values', # noqa: E501 + 'sparse_values': 'sparseValues', # noqa: E501 + 'metadata': 'metadata', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 + """ScoredVector - a model defined in OpenAPI + + Args: + id (str): This is the vector's unique id. + + 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,) + score (float): This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.. [optional] # noqa: E501 + values ([float]): This is the vector data, if it is requested.. [optional] # noqa: E501 + sparse_values (SparseValues): [optional] # noqa: E501 + metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata, if it is requested.. [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 ApiTypeError( + "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 + """ScoredVector - a model defined in OpenAPI + + Args: + id (str): This is the vector's unique id. + + 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,) + score (float): This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.. [optional] # noqa: E501 + values ([float]): This is the vector data, if it is requested.. [optional] # noqa: E501 + sparse_values (SparseValues): [optional] # noqa: E501 + metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata, if it is requested.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/single_query_results.py b/pinecone/core/client/model/single_query_results.py new file mode 100644 index 000000000..0c7415621 --- /dev/null +++ b/pinecone/core/client/model/single_query_results.py @@ -0,0 +1,266 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.scored_vector import ScoredVector + globals()['ScoredVector'] = ScoredVector + + +class SingleQueryResults(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'matches': ([ScoredVector],), # noqa: E501 + 'namespace': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'matches': 'matches', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SingleQueryResults - 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,) + matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 + namespace (str): The namespace for the vectors.. [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 ApiTypeError( + "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 + """SingleQueryResults - 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,) + matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 + namespace (str): The namespace for the vectors.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/sparse_values.py b/pinecone/core/client/model/sparse_values.py new file mode 100644 index 000000000..4d619531a --- /dev/null +++ b/pinecone/core/client/model/sparse_values.py @@ -0,0 +1,272 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class SparseValues(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 = { + ('indices',): { + }, + ('values',): { + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'indices': ([int],), # noqa: E501 + 'values': ([float],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'indices': 'indices', # noqa: E501 + 'values': 'values', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, indices, values, *args, **kwargs): # noqa: E501 + """SparseValues - a model defined in OpenAPI + + Args: + indices ([int]): The indices of the sparse data. + values ([float]): The corresponding values of the sparse data, which must be with the same length as the indices. + + 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 ApiTypeError( + "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.indices = indices + self.values = values + 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, indices, values, *args, **kwargs): # noqa: E501 + """SparseValues - a model defined in OpenAPI + + Args: + indices ([int]): The indices of the sparse data. + values ([float]): The corresponding values of the sparse data, which must be with the same length as the indices. + + 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 ApiTypeError( + "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.indices = indices + self.values = values + 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 ApiAttributeError(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/client/model/update_request.py b/pinecone/core/client/model/update_request.py new file mode 100644 index 000000000..1aec2bd88 --- /dev/null +++ b/pinecone/core/client/model/update_request.py @@ -0,0 +1,290 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.sparse_values import SparseValues + globals()['SparseValues'] = SparseValues + + +class UpdateRequest(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 = { + ('id',): { + 'max_length': 512, + 'min_length': 1, + }, + ('values',): { + }, + } + + @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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'id': (str,), # noqa: E501 + 'values': ([float],), # noqa: E501 + 'sparse_values': (SparseValues,), # noqa: E501 + 'set_metadata': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'namespace': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'values': 'values', # noqa: E501 + 'sparse_values': 'sparseValues', # noqa: E501 + 'set_metadata': 'setMetadata', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 + """UpdateRequest - a model defined in OpenAPI + + Args: + id (str): Vector's unique id. + + 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 ([float]): Vector data.. [optional] # noqa: E501 + sparse_values (SparseValues): [optional] # noqa: E501 + set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 + namespace (str): Namespace name where to update the vector.. [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 ApiTypeError( + "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 + """UpdateRequest - a model defined in OpenAPI + + Args: + id (str): Vector's unique id. + + 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 ([float]): Vector data.. [optional] # noqa: E501 + sparse_values (SparseValues): [optional] # noqa: E501 + set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 + namespace (str): Namespace name where to update the vector.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/upsert_request.py b/pinecone/core/client/model/upsert_request.py new file mode 100644 index 000000000..0ebf0aaed --- /dev/null +++ b/pinecone/core/client/model/upsert_request.py @@ -0,0 +1,274 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.vector import Vector + globals()['Vector'] = Vector + + +class UpsertRequest(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 = { + ('vectors',): { + }, + } + + @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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'vectors': ([Vector],), # noqa: E501 + 'namespace': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'vectors': 'vectors', # noqa: E501 + 'namespace': 'namespace', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, vectors, *args, **kwargs): # noqa: E501 + """UpsertRequest - a model defined in OpenAPI + + Args: + vectors ([Vector]): An array containing the vectors to upsert. Recommended batch limit is 100 vectors. + + 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,) + namespace (str): This is the namespace name where you upsert vectors.. [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 ApiTypeError( + "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.vectors = vectors + 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, vectors, *args, **kwargs): # noqa: E501 + """UpsertRequest - a model defined in OpenAPI + + Args: + vectors ([Vector]): An array containing the vectors to upsert. Recommended batch limit is 100 vectors. + + 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,) + namespace (str): This is the namespace name where you upsert vectors.. [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 ApiTypeError( + "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.vectors = vectors + 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 ApiAttributeError(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/client/model/upsert_response.py b/pinecone/core/client/model/upsert_response.py new file mode 100644 index 000000000..831fb39bb --- /dev/null +++ b/pinecone/core/client/model/upsert_response.py @@ -0,0 +1,256 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class UpsertResponse(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'upserted_count': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'upserted_count': 'upsertedCount', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """UpsertResponse - 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,) + upserted_count (int): The number of vectors upserted.. [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 ApiTypeError( + "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 + """UpsertResponse - 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,) + upserted_count (int): The number of vectors upserted.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/vector.py b/pinecone/core/client/model/vector.py new file mode 100644 index 000000000..e3aef790a --- /dev/null +++ b/pinecone/core/client/model/vector.py @@ -0,0 +1,288 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.sparse_values import SparseValues + globals()['SparseValues'] = SparseValues + + +class Vector(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 = { + ('id',): { + 'max_length': 512, + 'min_length': 1, + }, + ('values',): { + }, + } + + @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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'id': (str,), # noqa: E501 + 'values': ([float],), # noqa: E501 + 'sparse_values': (SparseValues,), # noqa: E501 + 'metadata': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'values': 'values', # noqa: E501 + 'sparse_values': 'sparseValues', # noqa: E501 + 'metadata': 'metadata', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, id, values, *args, **kwargs): # noqa: E501 + """Vector - a model defined in OpenAPI + + Args: + id (str): This is the vector's unique id. + values ([float]): This is the vector data included in the 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,) + sparse_values (SparseValues): [optional] # noqa: E501 + metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata included in the request.. [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 ApiTypeError( + "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.values = values + 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, values, *args, **kwargs): # noqa: E501 + """Vector - a model defined in OpenAPI + + Args: + id (str): This is the vector's unique id. + values ([float]): This is the vector data included in the 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,) + sparse_values (SparseValues): [optional] # noqa: E501 + metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): This is the metadata included in the request.. [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 ApiTypeError( + "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.values = values + 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 ApiAttributeError(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/client/model_utils.py b/pinecone/core/client/model_utils.py new file mode 100644 index 000000000..940cc93a1 --- /dev/null +++ b/pinecone/core/client/model_utils.py @@ -0,0 +1,1993 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +import inspect +import io +import os +import pprint +import re +import tempfile + +from dateutil.parser import parse + +from pinecone.core.client.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on function methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.get(attr) + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: 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 the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + return new_inst + + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: 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 the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + 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 variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + 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 variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + 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 variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + 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 variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if configuration: + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], + model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], '_data_store') else item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/pinecone/core/client/models/__init__.py b/pinecone/core/client/models/__init__.py index 85b949812..5c2079103 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -1,47 +1,38 @@ -# coding: utf-8 - # flake8: noqa -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 +# import all models into this package +# if you have many models here with many references from one model to another this may +# raise a RecursionError +# to avoid this, import only the models that you directly need like: +# from from pinecone.core.client.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) -# import models into model package -from pinecone.core.client.models.approximated_config import ApproximatedConfig -from pinecone.core.client.models.collection_meta import CollectionMeta -from pinecone.core.client.models.create_collection_request import CreateCollectionRequest -from pinecone.core.client.models.create_request import CreateRequest -from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig -from pinecone.core.client.models.delete_request import DeleteRequest -from pinecone.core.client.models.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.models.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.models.fetch_response import FetchResponse -from pinecone.core.client.models.hnsw_config import HnswConfig -from pinecone.core.client.models.index_meta import IndexMeta -from pinecone.core.client.models.index_meta_database import IndexMetaDatabase -from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig -from pinecone.core.client.models.index_meta_status import IndexMetaStatus -from pinecone.core.client.models.list_indexes200_response import ListIndexes200Response -from pinecone.core.client.models.namespace_summary import NamespaceSummary -from pinecone.core.client.models.patch_request import PatchRequest -from pinecone.core.client.models.protobuf_any import ProtobufAny -from pinecone.core.client.models.protobuf_null_value import ProtobufNullValue -from pinecone.core.client.models.query_request import QueryRequest -from pinecone.core.client.models.query_response import QueryResponse -from pinecone.core.client.models.query_vector import QueryVector -from pinecone.core.client.models.rpc_status import RpcStatus -from pinecone.core.client.models.scored_vector import ScoredVector -from pinecone.core.client.models.single_query_results import SingleQueryResults -from pinecone.core.client.models.sparse_values import SparseValues -from pinecone.core.client.models.update_request import UpdateRequest -from pinecone.core.client.models.upsert_request import UpsertRequest -from pinecone.core.client.models.upsert_response import UpsertResponse -from pinecone.core.client.models.vector import Vector +from pinecone.core.client.model.approximated_config import ApproximatedConfig +from pinecone.core.client.model.collection_meta import CollectionMeta +from pinecone.core.client.model.create_collection_request import CreateCollectionRequest +from pinecone.core.client.model.create_request import CreateRequest +from pinecone.core.client.model.delete_request import DeleteRequest +from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.model.fetch_response import FetchResponse +from pinecone.core.client.model.hnsw_config import HnswConfig +from pinecone.core.client.model.index_meta import IndexMeta +from pinecone.core.client.model.index_meta_database import IndexMetaDatabase +from pinecone.core.client.model.index_meta_status import IndexMetaStatus +from pinecone.core.client.model.namespace_summary import NamespaceSummary +from pinecone.core.client.model.patch_request import PatchRequest +from pinecone.core.client.model.protobuf_any import ProtobufAny +from pinecone.core.client.model.protobuf_null_value import ProtobufNullValue +from pinecone.core.client.model.query_request import QueryRequest +from pinecone.core.client.model.query_response import QueryResponse +from pinecone.core.client.model.query_vector import QueryVector +from pinecone.core.client.model.rpc_status import RpcStatus +from pinecone.core.client.model.scored_vector import ScoredVector +from pinecone.core.client.model.single_query_results import SingleQueryResults +from pinecone.core.client.model.sparse_values import SparseValues +from pinecone.core.client.model.update_request import UpdateRequest +from pinecone.core.client.model.upsert_request import UpsertRequest +from pinecone.core.client.model.upsert_response import UpsertResponse +from pinecone.core.client.model.vector import Vector diff --git a/pinecone/core/client/models/approximated_config.py b/pinecone/core/client/models/approximated_config.py deleted file mode 100644 index 3a478f77d..000000000 --- a/pinecone/core/client/models/approximated_config.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import BaseModel, StrictBool, StrictInt - - -class ApproximatedConfig(BaseModel): - """ - ApproximatedConfig - """ - - k_bits: Optional[StrictInt] = 512 - hybrid: Optional[StrictBool] = False - __properties = ["k_bits", "hybrid"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> ApproximatedConfig: - """Create an instance of ApproximatedConfig from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ApproximatedConfig: - """Create an instance of ApproximatedConfig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ApproximatedConfig.parse_obj(obj) - - _obj = ApproximatedConfig.parse_obj( - { - "k_bits": obj.get("k_bits") if obj.get("k_bits") is not None else 512, - "hybrid": obj.get("hybrid") if obj.get("hybrid") is not None else False, - } - ) - return _obj diff --git a/pinecone/core/client/models/collection_meta.py b/pinecone/core/client/models/collection_meta.py deleted file mode 100644 index 98ef3b0bd..000000000 --- a/pinecone/core/client/models/collection_meta.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from pydantic import BaseModel, Field, StrictInt, StrictStr - - -class CollectionMeta(BaseModel): - """ - CollectionMeta - """ - - name: StrictStr = Field(...) - size: StrictInt = Field(..., description="The size of the collection in bytes.") - status: StrictStr = Field(..., description="The status of the collection.") - dimension: StrictInt = Field(..., description="The dimension of the records stored in the collection") - vector_count: StrictInt = Field(..., description="The number of records stored in the collection") - __properties = ["name", "size", "status", "dimension", "vector_count"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> CollectionMeta: - """Create an instance of CollectionMeta from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CollectionMeta: - """Create an instance of CollectionMeta from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CollectionMeta.parse_obj(obj) - - _obj = CollectionMeta.parse_obj( - { - "name": obj.get("name"), - "size": obj.get("size"), - "status": obj.get("status"), - "dimension": obj.get("dimension"), - "vector_count": obj.get("vector_count"), - } - ) - return _obj diff --git a/pinecone/core/client/models/create_collection_request.py b/pinecone/core/client/models/create_collection_request.py deleted file mode 100644 index 4ca482296..000000000 --- a/pinecone/core/client/models/create_collection_request.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from pydantic import BaseModel, Field, StrictStr - - -class CreateCollectionRequest(BaseModel): - """ - CreateCollectionRequest - """ - - name: StrictStr = Field(..., description="The name of the collection to be created.") - source: StrictStr = Field(..., description="The name of the index to be used as the source for the collection.") - __properties = ["name", "source"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> CreateCollectionRequest: - """Create an instance of CreateCollectionRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateCollectionRequest: - """Create an instance of CreateCollectionRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateCollectionRequest.parse_obj(obj) - - _obj = CreateCollectionRequest.parse_obj({"name": obj.get("name"), "source": obj.get("source")}) - return _obj diff --git a/pinecone/core/client/models/create_request.py b/pinecone/core/client/models/create_request.py deleted file mode 100644 index 87bedfd3a..000000000 --- a/pinecone/core/client/models/create_request.py +++ /dev/null @@ -1,149 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr, validator -from pinecone.core.client.models.create_request_index_config import CreateRequestIndexConfig - - -class CreateRequest(BaseModel): - """ - CreateRequest - """ - - name: StrictStr = Field( - ..., description="The name of the index to be created. The maximum length is 45 characters." - ) - dimension: StrictInt = Field(..., description="The dimensions of the vectors to be inserted in the index") - region: StrictStr = Field(..., description="The region where you would like your index to be created") - cloud: StrictStr = Field(..., description="The public cloud where you would like your index hosted") - capacity_mode: StrictStr = Field(..., description="The capacity mode for the index.") - index_type: Optional[StrictStr] = Field( - "approximated", description="The type of vector index. Pinecone supports 'approximated'." - ) - metric: Optional[StrictStr] = Field( - "cosine", - description="The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.", - ) - pods: Optional[StrictInt] = Field(1, description="The number of pods for the index to use,including replicas.") - replicas: Optional[StrictInt] = Field( - 1, - description="The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.", - ) - shards: Optional[StrictInt] = Field(1, description="The number of shards to be used in the index.") - pod_type: Optional[StrictStr] = Field( - "p1.x1", - description="The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.", - ) - index_config: Optional[CreateRequestIndexConfig] = None - metadata_config: Optional[Dict[str, Any]] = Field( - None, - description='Configuration for the behavior of Pinecone\'s internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {"indexed": ["example_metadata_field"]} ``` ', - ) - source_collection: Optional[StrictStr] = Field( - None, description="The name of the collection to create an index from" - ) - __properties = [ - "name", - "dimension", - "region", - "cloud", - "capacity_mode", - "index_type", - "metric", - "pods", - "replicas", - "shards", - "pod_type", - "index_config", - "metadata_config", - "source_collection", - ] - - @validator("cloud") - def cloud_validate_enum(cls, value): - """Validates the enum""" - if value not in ("gcp", "aws", "azure"): - raise ValueError("must be one of enum values ('gcp', 'aws', 'azure')") - return value - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> CreateRequest: - """Create an instance of CreateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of index_config - if self.index_config: - _dict["index_config"] = self.index_config.to_dict() - # set to None if metadata_config (nullable) is None - # and __fields_set__ contains the field - if self.metadata_config is None and "metadata_config" in self.__fields_set__: - _dict["metadata_config"] = None - - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> CreateRequest: - """Create an instance of CreateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return CreateRequest.parse_obj(obj) - - _obj = CreateRequest.parse_obj( - { - "name": obj.get("name"), - "dimension": obj.get("dimension"), - "region": obj.get("region"), - "cloud": obj.get("cloud"), - "capacity_mode": obj.get("capacity_mode"), - "index_type": obj.get("index_type") if obj.get("index_type") is not None else "approximated", - "metric": obj.get("metric") if obj.get("metric") is not None else "cosine", - "pods": obj.get("pods") if obj.get("pods") is not None else 1, - "replicas": obj.get("replicas") if obj.get("replicas") is not None else 1, - "shards": obj.get("shards") if obj.get("shards") is not None else 1, - "pod_type": obj.get("pod_type") if obj.get("pod_type") is not None else "p1.x1", - "index_config": CreateRequestIndexConfig.from_dict(obj.get("index_config")) - if obj.get("index_config") is not None - else None, - "metadata_config": obj.get("metadata_config"), - "source_collection": obj.get("source_collection"), - } - ) - return _obj diff --git a/pinecone/core/client/models/create_request_index_config.py b/pinecone/core/client/models/create_request_index_config.py deleted file mode 100644 index 091fd207e..000000000 --- a/pinecone/core/client/models/create_request_index_config.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from pinecone.core.client.models.approximated_config import ApproximatedConfig -from typing import Union, Any, List, TYPE_CHECKING -from pydantic import StrictStr, Field - -CREATEREQUESTINDEXCONFIG_ONE_OF_SCHEMAS = ["ApproximatedConfig"] - - -class CreateRequestIndexConfig(BaseModel): - """ - CreateRequestIndexConfig - """ - - # data type: ApproximatedConfig - oneof_schema_1_validator: Optional[ApproximatedConfig] = None - if TYPE_CHECKING: - actual_instance: Union[ApproximatedConfig] - else: - actual_instance: Any - one_of_schemas: List[str] = Field(CREATEREQUESTINDEXCONFIG_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator("actual_instance") - def actual_instance_must_validate_oneof(cls, v): - instance = CreateRequestIndexConfig.construct() - error_messages = [] - match = 0 - # validate data type: ApproximatedConfig - if not isinstance(v, ApproximatedConfig): - error_messages.append(f"Error! Input type `{type(v)}` is not `ApproximatedConfig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - elif match == 0: - # no match - raise ValueError( - "No match found when setting `actual_instance` in CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> CreateRequestIndexConfig: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> CreateRequestIndexConfig: - """Returns the object represented by the json string""" - instance = CreateRequestIndexConfig.construct() - error_messages = [] - match = 0 - - # deserialize data into ApproximatedConfig - try: - instance.actual_instance = ApproximatedConfig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - elif match == 0: - # no match - raise ValueError( - "No match found when deserializing the JSON string into CreateRequestIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - else: - return instance - - def to_json(self) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance - - def to_str(self) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict()) diff --git a/pinecone/core/client/models/delete_request.py b/pinecone/core/client/models/delete_request.py deleted file mode 100644 index 9e189c8bf..000000000 --- a/pinecone/core/client/models/delete_request.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional -from pydantic import BaseModel, Field, StrictBool, StrictStr, conlist - - -class DeleteRequest(BaseModel): - """ - The request for the `Delete` operation. # noqa: E501 - """ - - ids: Optional[conlist(StrictStr)] = Field(None, description="Vectors to delete.") - delete_all: Optional[StrictBool] = Field( - False, - alias="deleteAll", - description="This indicates that all vectors in the index namespace should be deleted.", - ) - namespace: Optional[StrictStr] = Field(None, description="The namespace to delete vectors from, if applicable.") - filter: Optional[Dict[str, Any]] = Field( - None, - description="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/.", - ) - __properties = ["ids", "deleteAll", "namespace", "filter"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> DeleteRequest: - """Create an instance of DeleteRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DeleteRequest: - """Create an instance of DeleteRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DeleteRequest.parse_obj(obj) - - _obj = DeleteRequest.parse_obj( - { - "ids": obj.get("ids"), - "delete_all": obj.get("deleteAll") if obj.get("deleteAll") is not None else False, - "namespace": obj.get("namespace"), - "filter": obj.get("filter"), - } - ) - return _obj diff --git a/pinecone/core/client/models/describe_index_stats_request.py b/pinecone/core/client/models/describe_index_stats_request.py deleted file mode 100644 index 63a7e9b74..000000000 --- a/pinecone/core/client/models/describe_index_stats_request.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import BaseModel, Field - - -class DescribeIndexStatsRequest(BaseModel): - """ - The request for the `DescribeIndexStats` operation. # noqa: E501 - """ - - filter: Optional[Dict[str, Any]] = Field( - None, - description="If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.", - ) - __properties = ["filter"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> DescribeIndexStatsRequest: - """Create an instance of DescribeIndexStatsRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DescribeIndexStatsRequest: - """Create an instance of DescribeIndexStatsRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DescribeIndexStatsRequest.parse_obj(obj) - - _obj = DescribeIndexStatsRequest.parse_obj({"filter": obj.get("filter")}) - return _obj diff --git a/pinecone/core/client/models/describe_index_stats_response.py b/pinecone/core/client/models/describe_index_stats_response.py deleted file mode 100644 index 7a35ae470..000000000 --- a/pinecone/core/client/models/describe_index_stats_response.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Dict, Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt -from pinecone.core.client.models.namespace_summary import NamespaceSummary - - -class DescribeIndexStatsResponse(BaseModel): - """ - The response for the `DescribeIndexStats` operation. # noqa: E501 - """ - - namespaces: Optional[Dict[str, NamespaceSummary]] = Field( - None, - description="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.", - ) - dimension: Optional[StrictInt] = Field(None, description="The dimension of the indexed vectors.") - index_fullness: Optional[Union[StrictFloat, StrictInt]] = Field( - None, - alias="indexFullness", - description="The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%.", - ) - total_vector_count: Optional[StrictInt] = Field(None, alias="totalVectorCount") - __properties = ["namespaces", "dimension", "indexFullness", "totalVectorCount"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> DescribeIndexStatsResponse: - """Create an instance of DescribeIndexStatsResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each value in namespaces (dict) - _field_dict = {} - if self.namespaces: - for _key in self.namespaces: - if self.namespaces[_key]: - _field_dict[_key] = self.namespaces[_key].to_dict() - _dict["namespaces"] = _field_dict - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> DescribeIndexStatsResponse: - """Create an instance of DescribeIndexStatsResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return DescribeIndexStatsResponse.parse_obj(obj) - - _obj = DescribeIndexStatsResponse.parse_obj( - { - "namespaces": dict((_k, NamespaceSummary.from_dict(_v)) for _k, _v in obj.get("namespaces").items()) - if obj.get("namespaces") is not None - else None, - "dimension": obj.get("dimension"), - "index_fullness": obj.get("indexFullness"), - "total_vector_count": obj.get("totalVectorCount"), - } - ) - return _obj diff --git a/pinecone/core/client/models/fetch_response.py b/pinecone/core/client/models/fetch_response.py deleted file mode 100644 index 3763b572a..000000000 --- a/pinecone/core/client/models/fetch_response.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Dict, Optional -from pydantic import BaseModel, Field, StrictStr -from pinecone.core.client.models.vector import Vector - - -class FetchResponse(BaseModel): - """ - The response for the `Fetch` operation. # noqa: E501 - """ - - vectors: Optional[Dict[str, Vector]] = None - namespace: Optional[StrictStr] = Field(None, description="The namespace of the vectors.") - __properties = ["vectors", "namespace"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> FetchResponse: - """Create an instance of FetchResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each value in vectors (dict) - _field_dict = {} - if self.vectors: - for _key in self.vectors: - if self.vectors[_key]: - _field_dict[_key] = self.vectors[_key].to_dict() - _dict["vectors"] = _field_dict - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> FetchResponse: - """Create an instance of FetchResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return FetchResponse.parse_obj(obj) - - _obj = FetchResponse.parse_obj( - { - "vectors": dict((_k, Vector.from_dict(_v)) for _k, _v in obj.get("vectors").items()) - if obj.get("vectors") is not None - else None, - "namespace": obj.get("namespace"), - } - ) - return _obj diff --git a/pinecone/core/client/models/hnsw_config.py b/pinecone/core/client/models/hnsw_config.py deleted file mode 100644 index 75b7d6ce6..000000000 --- a/pinecone/core/client/models/hnsw_config.py +++ /dev/null @@ -1,78 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import BaseModel, Field, StrictInt - - -class HnswConfig(BaseModel): - """ - HnswConfig - """ - - ef_construction: Optional[StrictInt] = 500 - ef: Optional[StrictInt] = 250 - m: Optional[StrictInt] = Field(12, alias="M") - max_elements: Optional[StrictInt] = 50000000 - __properties = ["ef_construction", "ef", "M", "max_elements"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> HnswConfig: - """Create an instance of HnswConfig from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> HnswConfig: - """Create an instance of HnswConfig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return HnswConfig.parse_obj(obj) - - _obj = HnswConfig.parse_obj( - { - "ef_construction": obj.get("ef_construction") if obj.get("ef_construction") is not None else 500, - "ef": obj.get("ef") if obj.get("ef") is not None else 250, - "m": obj.get("M") if obj.get("M") is not None else 12, - "max_elements": obj.get("max_elements") if obj.get("max_elements") is not None else 50000000, - } - ) - return _obj diff --git a/pinecone/core/client/models/index_meta.py b/pinecone/core/client/models/index_meta.py deleted file mode 100644 index 348cf509d..000000000 --- a/pinecone/core/client/models/index_meta.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from pydantic import BaseModel, Field -from pinecone.core.client.models.index_meta_database import IndexMetaDatabase -from pinecone.core.client.models.index_meta_status import IndexMetaStatus - - -class IndexMeta(BaseModel): - """ - IndexMeta - """ - - database: IndexMetaDatabase = Field(...) - status: IndexMetaStatus = Field(...) - __properties = ["database", "status"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> IndexMeta: - """Create an instance of IndexMeta from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of database - if self.database: - _dict["database"] = self.database.to_dict() - # override the default output from pydantic by calling `to_dict()` of status - if self.status: - _dict["status"] = self.status.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> IndexMeta: - """Create an instance of IndexMeta from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return IndexMeta.parse_obj(obj) - - _obj = IndexMeta.parse_obj( - { - "database": IndexMetaDatabase.from_dict(obj.get("database")) - if obj.get("database") is not None - else None, - "status": IndexMetaStatus.from_dict(obj.get("status")) if obj.get("status") is not None else None, - } - ) - return _obj diff --git a/pinecone/core/client/models/index_meta_database.py b/pinecone/core/client/models/index_meta_database.py deleted file mode 100644 index 7d0970e1d..000000000 --- a/pinecone/core/client/models/index_meta_database.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr -from pinecone.core.client.models.index_meta_database_index_config import IndexMetaDatabaseIndexConfig - - -class IndexMetaDatabase(BaseModel): - """ - IndexMetaDatabase - """ - - name: StrictStr = Field(...) - dimension: StrictInt = Field(...) - capacity_mode: StrictStr = Field(...) - index_type: Optional[StrictStr] = None - metric: StrictStr = Field(...) - pods: Optional[StrictInt] = None - replicas: Optional[StrictInt] = None - shards: Optional[StrictInt] = None - pod_type: Optional[StrictStr] = None - index_config: Optional[IndexMetaDatabaseIndexConfig] = None - metadata_config: Optional[Dict[str, Any]] = None - __properties = [ - "name", - "dimension", - "capacity_mode", - "index_type", - "metric", - "pods", - "replicas", - "shards", - "pod_type", - "index_config", - "metadata_config", - ] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> IndexMetaDatabase: - """Create an instance of IndexMetaDatabase from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of index_config - if self.index_config: - _dict["index_config"] = self.index_config.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> IndexMetaDatabase: - """Create an instance of IndexMetaDatabase from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return IndexMetaDatabase.parse_obj(obj) - - _obj = IndexMetaDatabase.parse_obj( - { - "name": obj.get("name"), - "dimension": obj.get("dimension"), - "capacity_mode": obj.get("capacity_mode"), - "index_type": obj.get("index_type"), - "metric": obj.get("metric") if obj.get("metric") is not None else "cosine", - "pods": obj.get("pods"), - "replicas": obj.get("replicas"), - "shards": obj.get("shards"), - "pod_type": obj.get("pod_type"), - "index_config": IndexMetaDatabaseIndexConfig.from_dict(obj.get("index_config")) - if obj.get("index_config") is not None - else None, - "metadata_config": obj.get("metadata_config"), - } - ) - return _obj diff --git a/pinecone/core/client/models/index_meta_database_index_config.py b/pinecone/core/client/models/index_meta_database_index_config.py deleted file mode 100644 index d58d078e9..000000000 --- a/pinecone/core/client/models/index_meta_database_index_config.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 - -from typing import Any, List, Optional -from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from pinecone.core.client.models.approximated_config import ApproximatedConfig -from typing import Union, Any, List, TYPE_CHECKING -from pydantic import StrictStr, Field - -INDEXMETADATABASEINDEXCONFIG_ONE_OF_SCHEMAS = ["ApproximatedConfig"] - - -class IndexMetaDatabaseIndexConfig(BaseModel): - """ - IndexMetaDatabaseIndexConfig - """ - - # data type: ApproximatedConfig - oneof_schema_1_validator: Optional[ApproximatedConfig] = None - if TYPE_CHECKING: - actual_instance: Union[ApproximatedConfig] - else: - actual_instance: Any - one_of_schemas: List[str] = Field(INDEXMETADATABASEINDEXCONFIG_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator("actual_instance") - def actual_instance_must_validate_oneof(cls, v): - instance = IndexMetaDatabaseIndexConfig.construct() - error_messages = [] - match = 0 - # validate data type: ApproximatedConfig - if not isinstance(v, ApproximatedConfig): - error_messages.append(f"Error! Input type `{type(v)}` is not `ApproximatedConfig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - elif match == 0: - # no match - raise ValueError( - "No match found when setting `actual_instance` in IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> IndexMetaDatabaseIndexConfig: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> IndexMetaDatabaseIndexConfig: - """Returns the object represented by the json string""" - instance = IndexMetaDatabaseIndexConfig.construct() - error_messages = [] - match = 0 - - # deserialize data into ApproximatedConfig - try: - instance.actual_instance = ApproximatedConfig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - elif match == 0: - # no match - raise ValueError( - "No match found when deserializing the JSON string into IndexMetaDatabaseIndexConfig with oneOf schemas: ApproximatedConfig. Details: " - + ", ".join(error_messages) - ) - else: - return instance - - def to_json(self) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance - - def to_str(self) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict()) diff --git a/pinecone/core/client/models/index_meta_status.py b/pinecone/core/client/models/index_meta_status.py deleted file mode 100644 index fc76025c9..000000000 --- a/pinecone/core/client/models/index_meta_status.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, validator - - -class IndexMetaStatus(BaseModel): - """ - IndexMetaStatus - """ - - ready: StrictBool = Field(...) - state: StrictStr = Field(...) - host: StrictStr = Field(...) - port: StrictInt = Field(...) - __properties = ["ready", "state", "host", "port"] - - @validator("state") - def state_validate_enum(cls, value): - """Validates the enum""" - if value not in ( - "Initializing", - "InitializationFailed", - "ScalingUp", - "ScalingDown", - "ScalingUpPodSize", - "ScalingDownPodSize", - "Terminating", - "Ready", - ): - raise ValueError( - "must be one of enum values ('Initializing', 'InitializationFailed', 'ScalingUp', 'ScalingDown', 'ScalingUpPodSize', 'ScalingDownPodSize', 'Terminating', 'Ready')" - ) - return value - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> IndexMetaStatus: - """Create an instance of IndexMetaStatus from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> IndexMetaStatus: - """Create an instance of IndexMetaStatus from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return IndexMetaStatus.parse_obj(obj) - - _obj = IndexMetaStatus.parse_obj( - {"ready": obj.get("ready"), "state": obj.get("state"), "host": obj.get("host"), "port": obj.get("port")} - ) - return _obj diff --git a/pinecone/core/client/models/list_indexes200_response.py b/pinecone/core/client/models/list_indexes200_response.py deleted file mode 100644 index 9a94ef226..000000000 --- a/pinecone/core/client/models/list_indexes200_response.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, conlist -from pinecone.core.client.models.index_meta import IndexMeta - - -class ListIndexes200Response(BaseModel): - """ - ListIndexes200Response - """ - - databases: Optional[conlist(IndexMeta)] = None - __properties = ["databases"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> ListIndexes200Response: - """Create an instance of ListIndexes200Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in databases (list) - _items = [] - if self.databases: - for _item in self.databases: - if _item: - _items.append(_item.to_dict()) - _dict["databases"] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ListIndexes200Response: - """Create an instance of ListIndexes200Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ListIndexes200Response.parse_obj(obj) - - _obj = ListIndexes200Response.parse_obj( - { - "databases": [IndexMeta.from_dict(_item) for _item in obj.get("databases")] - if obj.get("databases") is not None - else None - } - ) - return _obj diff --git a/pinecone/core/client/models/namespace_summary.py b/pinecone/core/client/models/namespace_summary.py deleted file mode 100644 index 8d5fb118d..000000000 --- a/pinecone/core/client/models/namespace_summary.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import BaseModel, Field, StrictInt - - -class NamespaceSummary(BaseModel): - """ - A summary of the contents of a namespace. # noqa: E501 - """ - - vector_count: Optional[StrictInt] = Field( - None, - alias="vectorCount", - description="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.", - ) - __properties = ["vectorCount"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> NamespaceSummary: - """Create an instance of NamespaceSummary from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> NamespaceSummary: - """Create an instance of NamespaceSummary from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return NamespaceSummary.parse_obj(obj) - - _obj = NamespaceSummary.parse_obj({"vector_count": obj.get("vectorCount")}) - return _obj diff --git a/pinecone/core/client/models/patch_request.py b/pinecone/core/client/models/patch_request.py deleted file mode 100644 index 79ab8f29f..000000000 --- a/pinecone/core/client/models/patch_request.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr - - -class PatchRequest(BaseModel): - """ - PatchRequest - """ - - replicas: Optional[StrictInt] = Field(None, description="The desired number of replicas for the index.") - pod_type: Optional[StrictStr] = Field( - None, - description="The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.", - ) - __properties = ["replicas", "pod_type"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> PatchRequest: - """Create an instance of PatchRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> PatchRequest: - """Create an instance of PatchRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return PatchRequest.parse_obj(obj) - - _obj = PatchRequest.parse_obj({"replicas": obj.get("replicas"), "pod_type": obj.get("pod_type")}) - return _obj diff --git a/pinecone/core/client/models/protobuf_any.py b/pinecone/core/client/models/protobuf_any.py deleted file mode 100644 index d1114da90..000000000 --- a/pinecone/core/client/models/protobuf_any.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional, Union -from pydantic import BaseModel, Field, StrictBytes, StrictStr - - -class ProtobufAny(BaseModel): - """ - ProtobufAny - """ - - type_url: Optional[StrictStr] = Field(None, alias="typeUrl") - value: Optional[Union[StrictBytes, StrictStr]] = None - __properties = ["typeUrl", "value"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> ProtobufAny: - """Create an instance of ProtobufAny from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ProtobufAny: - """Create an instance of ProtobufAny from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ProtobufAny.parse_obj(obj) - - _obj = ProtobufAny.parse_obj({"type_url": obj.get("typeUrl"), "value": obj.get("value")}) - return _obj diff --git a/pinecone/core/client/models/protobuf_null_value.py b/pinecone/core/client/models/protobuf_null_value.py deleted file mode 100644 index e90b5bd47..000000000 --- a/pinecone/core/client/models/protobuf_null_value.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import json -import pprint -import re # noqa: F401 -from aenum import Enum, no_arg - - -class ProtobufNullValue(str, Enum): - """ - `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value. - """ - - """ - allowed enum values - """ - NULL_VALUE = "NULL_VALUE" - - @classmethod - def from_json(cls, json_str: str) -> ProtobufNullValue: - """Create an instance of ProtobufNullValue from a JSON string""" - return ProtobufNullValue(json.loads(json_str)) diff --git a/pinecone/core/client/models/query_request.py b/pinecone/core/client/models/query_request.py deleted file mode 100644 index 19787a26b..000000000 --- a/pinecone/core/client/models/query_request.py +++ /dev/null @@ -1,134 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, Field, StrictBool, StrictFloat, StrictInt, StrictStr, conint, conlist, constr -from pinecone.core.client.models.query_vector import QueryVector -from pinecone.core.client.models.sparse_values import SparseValues - - -class QueryRequest(BaseModel): - """ - The request for the `Query` operation. # noqa: E501 - """ - - namespace: Optional[StrictStr] = Field(None, description="The namespace to query.") - top_k: conint(strict=True, le=10000, ge=1) = Field( - ..., alias="topK", description="The number of results to return for each query." - ) - filter: Optional[Dict[str, Any]] = Field( - None, - description="The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.", - ) - include_values: Optional[StrictBool] = Field( - False, alias="includeValues", description="Indicates whether vector values are included in the response." - ) - include_metadata: Optional[StrictBool] = Field( - False, - alias="includeMetadata", - description="Indicates whether metadata is included in the response as well as the ids.", - ) - queries: Optional[conlist(QueryVector)] = Field( - None, - description="DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.", - ) - vector: Optional[conlist(Union[StrictFloat, StrictInt])] = Field( - None, - description="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`.", - ) - sparse_vector: Optional[SparseValues] = Field(None, alias="sparseVector") - id: Optional[constr(strict=True, max_length=512)] = Field( - None, - description="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`.", - ) - __properties = [ - "namespace", - "topK", - "filter", - "includeValues", - "includeMetadata", - "queries", - "vector", - "sparseVector", - "id", - ] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> QueryRequest: - """Create an instance of QueryRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in queries (list) - _items = [] - if self.queries: - for _item in self.queries: - if _item: - _items.append(_item.to_dict()) - _dict["queries"] = _items - # override the default output from pydantic by calling `to_dict()` of sparse_vector - if self.sparse_vector: - _dict["sparseVector"] = self.sparse_vector.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> QueryRequest: - """Create an instance of QueryRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return QueryRequest.parse_obj(obj) - - _obj = QueryRequest.parse_obj( - { - "namespace": obj.get("namespace"), - "top_k": obj.get("topK"), - "filter": obj.get("filter"), - "include_values": obj.get("includeValues") if obj.get("includeValues") is not None else False, - "include_metadata": obj.get("includeMetadata") if obj.get("includeMetadata") is not None else False, - "queries": [QueryVector.from_dict(_item) for _item in obj.get("queries")] - if obj.get("queries") is not None - else None, - "vector": obj.get("vector"), - "sparse_vector": SparseValues.from_dict(obj.get("sparseVector")) - if obj.get("sparseVector") is not None - else None, - "id": obj.get("id"), - } - ) - return _obj diff --git a/pinecone/core/client/models/query_response.py b/pinecone/core/client/models/query_response.py deleted file mode 100644 index 5c4f6bf27..000000000 --- a/pinecone/core/client/models/query_response.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist -from pinecone.core.client.models.scored_vector import ScoredVector -from pinecone.core.client.models.single_query_results import SingleQueryResults - - -class QueryResponse(BaseModel): - """ - 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. # noqa: E501 - """ - - results: Optional[conlist(SingleQueryResults)] = Field( - None, description="DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`." - ) - matches: Optional[conlist(ScoredVector)] = Field(None, description="The matches for the vectors.") - namespace: Optional[StrictStr] = Field(None, description="The namespace for the vectors.") - __properties = ["results", "matches", "namespace"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> QueryResponse: - """Create an instance of QueryResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in results (list) - _items = [] - if self.results: - for _item in self.results: - if _item: - _items.append(_item.to_dict()) - _dict["results"] = _items - # override the default output from pydantic by calling `to_dict()` of each item in matches (list) - _items = [] - if self.matches: - for _item in self.matches: - if _item: - _items.append(_item.to_dict()) - _dict["matches"] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> QueryResponse: - """Create an instance of QueryResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return QueryResponse.parse_obj(obj) - - _obj = QueryResponse.parse_obj( - { - "results": [SingleQueryResults.from_dict(_item) for _item in obj.get("results")] - if obj.get("results") is not None - else None, - "matches": [ScoredVector.from_dict(_item) for _item in obj.get("matches")] - if obj.get("matches") is not None - else None, - "namespace": obj.get("namespace"), - } - ) - return _obj diff --git a/pinecone/core/client/models/query_vector.py b/pinecone/core/client/models/query_vector.py deleted file mode 100644 index 544bc6fd5..000000000 --- a/pinecone/core/client/models/query_vector.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr, conint, conlist -from pinecone.core.client.models.sparse_values import SparseValues - - -class QueryVector(BaseModel): - """ - A single query vector within a `QueryRequest`. # noqa: E501 - """ - - values: conlist(Union[StrictFloat, StrictInt]) = Field( - ..., - description="The query vector values. This should be the same length as the dimension of the index being queried.", - ) - sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") - top_k: Optional[conint(strict=True, le=10000, ge=1)] = Field( - None, alias="topK", description="An override for the number of results to return for this query vector." - ) - namespace: Optional[StrictStr] = Field(None, description="An override the namespace to search.") - filter: Optional[Dict[str, Any]] = Field( - None, description="An override for the metadata filter to apply. This replaces the request-level filter." - ) - __properties = ["values", "sparseValues", "topK", "namespace", "filter"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> QueryVector: - """Create an instance of QueryVector from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sparse_values - if self.sparse_values: - _dict["sparseValues"] = self.sparse_values.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> QueryVector: - """Create an instance of QueryVector from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return QueryVector.parse_obj(obj) - - _obj = QueryVector.parse_obj( - { - "values": obj.get("values"), - "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) - if obj.get("sparseValues") is not None - else None, - "top_k": obj.get("topK"), - "namespace": obj.get("namespace"), - "filter": obj.get("filter"), - } - ) - return _obj diff --git a/pinecone/core/client/models/rpc_status.py b/pinecone/core/client/models/rpc_status.py deleted file mode 100644 index e02eadb6c..000000000 --- a/pinecone/core/client/models/rpc_status.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, conlist -from pinecone.core.client.models.protobuf_any import ProtobufAny - - -class RpcStatus(BaseModel): - """ - RpcStatus - """ - - code: Optional[StrictInt] = None - message: Optional[StrictStr] = None - details: Optional[conlist(ProtobufAny)] = None - __properties = ["code", "message", "details"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> RpcStatus: - """Create an instance of RpcStatus from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in details (list) - _items = [] - if self.details: - for _item in self.details: - if _item: - _items.append(_item.to_dict()) - _dict["details"] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> RpcStatus: - """Create an instance of RpcStatus from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return RpcStatus.parse_obj(obj) - - _obj = RpcStatus.parse_obj( - { - "code": obj.get("code"), - "message": obj.get("message"), - "details": [ProtobufAny.from_dict(_item) for _item in obj.get("details")] - if obj.get("details") is not None - else None, - } - ) - return _obj diff --git a/pinecone/core/client/models/scored_vector.py b/pinecone/core/client/models/scored_vector.py deleted file mode 100644 index bf983eae6..000000000 --- a/pinecone/core/client/models/scored_vector.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist, constr -from pinecone.core.client.models.sparse_values import SparseValues - - -class ScoredVector(BaseModel): - """ - ScoredVector - """ - - id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="This is the vector's unique id.") - score: Optional[Union[StrictFloat, StrictInt]] = Field( - None, - description="This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.", - ) - values: Optional[conlist(Union[StrictFloat, StrictInt])] = Field( - None, description="This is the vector data, if it is requested." - ) - sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") - metadata: Optional[Dict[str, Any]] = Field(None, description="This is the metadata, if it is requested.") - __properties = ["id", "score", "values", "sparseValues", "metadata"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> ScoredVector: - """Create an instance of ScoredVector from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sparse_values - if self.sparse_values: - _dict["sparseValues"] = self.sparse_values.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ScoredVector: - """Create an instance of ScoredVector from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ScoredVector.parse_obj(obj) - - _obj = ScoredVector.parse_obj( - { - "id": obj.get("id"), - "score": obj.get("score"), - "values": obj.get("values"), - "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) - if obj.get("sparseValues") is not None - else None, - "metadata": obj.get("metadata"), - } - ) - return _obj diff --git a/pinecone/core/client/models/single_query_results.py b/pinecone/core/client/models/single_query_results.py deleted file mode 100644 index 91ef3c00b..000000000 --- a/pinecone/core/client/models/single_query_results.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist -from pinecone.core.client.models.scored_vector import ScoredVector - - -class SingleQueryResults(BaseModel): - """ - SingleQueryResults - """ - - matches: Optional[conlist(ScoredVector)] = Field(None, description="The matches for the vectors.") - namespace: Optional[StrictStr] = Field(None, description="The namespace for the vectors.") - __properties = ["matches", "namespace"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> SingleQueryResults: - """Create an instance of SingleQueryResults from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in matches (list) - _items = [] - if self.matches: - for _item in self.matches: - if _item: - _items.append(_item.to_dict()) - _dict["matches"] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SingleQueryResults: - """Create an instance of SingleQueryResults from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SingleQueryResults.parse_obj(obj) - - _obj = SingleQueryResults.parse_obj( - { - "matches": [ScoredVector.from_dict(_item) for _item in obj.get("matches")] - if obj.get("matches") is not None - else None, - "namespace": obj.get("namespace"), - } - ) - return _obj diff --git a/pinecone/core/client/models/sparse_values.py b/pinecone/core/client/models/sparse_values.py deleted file mode 100644 index c72173d33..000000000 --- a/pinecone/core/client/models/sparse_values.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist - - -class SparseValues(BaseModel): - """ - Vector sparse data. Represented as a list of indices and a list of corresponded values, which must be with the same length. # noqa: E501 - """ - - indices: conlist(StrictInt) = Field(..., description="The indices of the sparse data.") - values: conlist(Union[StrictFloat, StrictInt]) = Field( - ..., - description="The corresponding values of the sparse data, which must be with the same length as the indices.", - ) - __properties = ["indices", "values"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> SparseValues: - """Create an instance of SparseValues from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> SparseValues: - """Create an instance of SparseValues from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return SparseValues.parse_obj(obj) - - _obj = SparseValues.parse_obj({"indices": obj.get("indices"), "values": obj.get("values")}) - return _obj diff --git a/pinecone/core/client/models/update_request.py b/pinecone/core/client/models/update_request.py deleted file mode 100644 index a04a39208..000000000 --- a/pinecone/core/client/models/update_request.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr, conlist, constr -from pinecone.core.client.models.sparse_values import SparseValues - - -class UpdateRequest(BaseModel): - """ - The request for the `Upsert` operation. # noqa: E501 - """ - - id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="Vector's unique id.") - values: Optional[conlist(Union[StrictFloat, StrictInt])] = Field(None, description="Vector data.") - sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") - set_metadata: Optional[Dict[str, Any]] = Field( - None, alias="setMetadata", description="Metadata to *set* for the vector." - ) - namespace: Optional[StrictStr] = Field(None, description="Namespace name where to update the vector.") - __properties = ["id", "values", "sparseValues", "setMetadata", "namespace"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> UpdateRequest: - """Create an instance of UpdateRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sparse_values - if self.sparse_values: - _dict["sparseValues"] = self.sparse_values.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> UpdateRequest: - """Create an instance of UpdateRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return UpdateRequest.parse_obj(obj) - - _obj = UpdateRequest.parse_obj( - { - "id": obj.get("id"), - "values": obj.get("values"), - "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) - if obj.get("sparseValues") is not None - else None, - "set_metadata": obj.get("setMetadata"), - "namespace": obj.get("namespace"), - } - ) - return _obj diff --git a/pinecone/core/client/models/upsert_request.py b/pinecone/core/client/models/upsert_request.py deleted file mode 100644 index 11518db50..000000000 --- a/pinecone/core/client/models/upsert_request.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist -from pinecone.core.client.models.vector import Vector - - -class UpsertRequest(BaseModel): - """ - The request for the `Upsert` operation. # noqa: E501 - """ - - vectors: conlist(Vector) = Field( - ..., description="An array containing the vectors to upsert. Recommended batch limit is 100 vectors." - ) - namespace: Optional[StrictStr] = Field(None, description="This is the namespace name where you upsert vectors.") - __properties = ["vectors", "namespace"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> UpsertRequest: - """Create an instance of UpsertRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in vectors (list) - _items = [] - if self.vectors: - for _item in self.vectors: - if _item: - _items.append(_item.to_dict()) - _dict["vectors"] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> UpsertRequest: - """Create an instance of UpsertRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return UpsertRequest.parse_obj(obj) - - _obj = UpsertRequest.parse_obj( - { - "vectors": [Vector.from_dict(_item) for _item in obj.get("vectors")] - if obj.get("vectors") is not None - else None, - "namespace": obj.get("namespace"), - } - ) - return _obj diff --git a/pinecone/core/client/models/upsert_response.py b/pinecone/core/client/models/upsert_response.py deleted file mode 100644 index cd17799e4..000000000 --- a/pinecone/core/client/models/upsert_response.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Optional -from pydantic import BaseModel, Field, StrictInt - - -class UpsertResponse(BaseModel): - """ - The response for the `Upsert` operation. # noqa: E501 - """ - - upserted_count: Optional[StrictInt] = Field( - None, alias="upsertedCount", description="The number of vectors upserted." - ) - __properties = ["upsertedCount"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> UpsertResponse: - """Create an instance of UpsertResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> UpsertResponse: - """Create an instance of UpsertResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return UpsertResponse.parse_obj(obj) - - _obj = UpsertResponse.parse_obj({"upserted_count": obj.get("upsertedCount")}) - return _obj diff --git a/pinecone/core/client/models/vector.py b/pinecone/core/client/models/vector.py deleted file mode 100644 index 963751811..000000000 --- a/pinecone/core/client/models/vector.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding: utf-8 - -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - - -from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, conlist, constr -from pinecone.core.client.models.sparse_values import SparseValues - - -class Vector(BaseModel): - """ - Vector - """ - - id: constr(strict=True, max_length=512, min_length=1) = Field(..., description="This is the vector's unique id.") - values: conlist(Union[StrictFloat, StrictInt]) = Field( - ..., description="This is the vector data included in the request." - ) - sparse_values: Optional[SparseValues] = Field(None, alias="sparseValues") - metadata: Optional[Dict[str, Any]] = Field(None, description="This is the metadata included in the request.") - __properties = ["id", "values", "sparseValues", "metadata"] - - class Config: - """Pydantic configuration""" - - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Vector: - """Create an instance of Vector from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of sparse_values - if self.sparse_values: - _dict["sparseValues"] = self.sparse_values.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> Vector: - """Create an instance of Vector from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return Vector.parse_obj(obj) - - _obj = Vector.parse_obj( - { - "id": obj.get("id"), - "values": obj.get("values"), - "sparse_values": SparseValues.from_dict(obj.get("sparseValues")) - if obj.get("sparseValues") is not None - else None, - "metadata": obj.get("metadata"), - } - ) - return _obj diff --git a/pinecone/core/client/py.typed b/pinecone/core/client/py.typed deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index 4cbc0c0d0..8a9aafcb6 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -1,16 +1,12 @@ -# coding: utf-8 - """ Pinecone API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: version not set Contact: support@pinecone.io - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 + Generated by: https://openapi-generator.tech +""" import io @@ -18,26 +14,19 @@ import logging import re import ssl +from urllib.parse import urlencode -from urllib.parse import urlencode, quote_plus import urllib3 -from pinecone.core.client.exceptions import ( - ApiException, - UnauthorizedException, - ForbiddenException, - NotFoundException, - ServiceException, - ApiValueError, - BadRequestException, -) +from pinecone.core.client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): - def __init__(self, resp) -> None: + + def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason @@ -45,15 +34,16 @@ def __init__(self, resp) -> None: def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers + return self.urllib3_response.getheaders() def getheader(self, name, default=None): """Returns a given response header.""" return self.urllib3_response.headers.get(name, default) -class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 @@ -68,16 +58,13 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args["assert_hostname"] = configuration.assert_hostname # noqa: E501 + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if configuration.retries is not None: - addition_pool_args["retries"] = configuration.retries - - if configuration.tls_server_name: - addition_pool_args["server_hostname"] = configuration.tls_server_name + addition_pool_args['retries'] = configuration.retries if configuration.socket_options is not None: - addition_pool_args["socket_options"] = configuration.socket_options + addition_pool_args['socket_options'] = configuration.socket_options if maxsize is None: if configuration.connection_pool_maxsize is not None: @@ -96,7 +83,7 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: key_file=configuration.key_file, proxy_url=configuration.proxy, proxy_headers=configuration.proxy_headers, - **addition_pool_args, + **addition_pool_args ) else: self.pool_manager = urllib3.PoolManager( @@ -106,20 +93,12 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, - **addition_pool_args, + **addition_pool_args ) - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): """Perform requests. :param method: http request method @@ -139,77 +118,75 @@ def request( (connection, read) timeouts. """ method = method.upper() - assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] if post_params and body: - raise ApiValueError("body parameter cannot be used with post_params parameter.") + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: - # no content type provided or payload is json - if not headers.get("Content-Type") or re.search("json", headers["Content-Type"], re.IGNORECASE): + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' + if query_params: + url += '?' + urlencode(query_params) + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, - url, + method, url, body=request_body, preload_content=_preload_content, timeout=timeout, - headers=headers, - ) - elif headers["Content-Type"] == "application/x-www-form-urlencoded": # noqa: E501 + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( - method, - url, + method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, timeout=timeout, - headers=headers, - ) - elif headers["Content-Type"] == "multipart/form-data": + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. - del headers["Content-Type"] + del headers['Content-Type'] r = self.pool_manager.request( - method, - url, + method, url, fields=post_params, encode_multipart=True, preload_content=_preload_content, timeout=timeout, - headers=headers, - ) + headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form elif isinstance(body, str) or isinstance(body, bytes): request_body = body r = self.pool_manager.request( - method, - url, + method, url, body=request_body, preload_content=_preload_content, timeout=timeout, - headers=headers, - ) + headers=headers) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided @@ -218,9 +195,11 @@ def request( raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request( - method, url, fields={}, preload_content=_preload_content, timeout=timeout, headers=headers - ) + r = self.pool_manager.request(method, url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) @@ -232,9 +211,6 @@ def request( logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - if r.status == 401: raise UnauthorizedException(http_resp=r) @@ -251,119 +227,67 @@ def request( return r - def get_request(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def options_request( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def delete_request( - self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None - ): - return self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def post_request( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def put_request( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def patch_request( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PATCH", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) diff --git a/pinecone/core/grpc/protos/vector_service_pb2.py b/pinecone/core/grpc/protos/vector_service_pb2.py index 276c606d9..665ead6c7 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.py +++ b/pinecone/core/grpc/protos/vector_service_pb2.py @@ -6,7 +6,6 @@ from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database - # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() @@ -19,1905 +18,1211 @@ DESCRIPTOR = _descriptor.FileDescriptor( - name="vector_service.proto", - package="", - syntax="proto3", - serialized_options=b'\n\021io.pinecone.protoP\001Z/github.com/pinecone-io/new-go-pinecone/pinecone\222A\366\002\022K\n\014Pinecone API";\n\017Pinecone.io Ops\022\023https://pinecone.io\032\023support@pinecone.io\0329{index_name}-{project_name}.svc.{environment}.pinecone.io*\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', - create_key=_descriptor._internal_create_key, - serialized_pb=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"~\n\x0cSparseValues\x12\x35\n\x07indices\x18\x01 \x03(\rB$\x92\x41\x1eJ\x16[1, 312, 822, 14, 980]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12\x37\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\xe0\x41\x02"\xfd\x01\n\x06Vector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe0\x41\x02\x12G\n\x06values\x18\x02 \x03(\x02\x42\x37\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\xe0\x41\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}"\x93\x02\n\x0cScoredVector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe0\x41\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}"d\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x0c\x92\x41\x06x\xe8\x07\x80\x01\x01\xe0\x41\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"h\n\x0c\x46\x65tchRequest\x12+\n\x03ids\x18\x01 \x03(\tB\x1e\x92\x41\x18J\x10["id-0", "id-1"]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13"example-namespace""\xa3\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"\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"\xd0\x02\n\x0bQueryVector\x12G\n\x06values\x18\x01 \x03(\x02\x42\x37\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\xe0\x41\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}}"\xfa\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\x1c\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\xe0\x41\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""l\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"\xb2\x02\n\rUpdateRequest\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12"example-vector-1"x\x80\x04\x80\x01\x01\xe0\x41\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\xbd\x05\n\rVectorService\x12\x63\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse"8\x82\xd3\xe4\x93\x02\x14"\x0f/vectors/upsert:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06upsert\x12v\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse"K\x82\xd3\xe4\x93\x02\'"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x92\x41\x1b\n\x11Vector Operations*\x06\x64\x65lete\x12[\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse"3\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x92\x41\x1a\n\x11Vector Operations*\x05\x66\x65tch\x12V\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse".\x82\xd3\xe4\x93\x02\x0b"\x06/query:\x01*\x92\x41\x1a\n\x11Vector Operations*\x05query\x12\x63\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse"8\x82\xd3\xe4\x93\x02\x14"\x0f/vectors/update:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06update\x12\xb4\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse"e\x82\xd3\xe4\x93\x02\x33"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_stats\x92\x41)\n\x11Vector Operations*\x14\x64\x65scribe_index_statsB\xc0\x03\n\x11io.pinecone.protoP\x01Z/github.com/pinecone-io/new-go-pinecone/pinecone\x92\x41\xf6\x02\x12K\n\x0cPinecone API";\n\x0fPinecone.io Ops\x12\x13https://pinecone.io\x1a\x13support@pinecone.io\x1a\x39{index_name}-{project_name}.svc.{environment}.pinecone.io*\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', - dependencies=[ - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - protoc__gen__openapiv2_dot_options_dot_annotations__pb2.DESCRIPTOR, - ], -) + name='vector_service.proto', + package='', + syntax='proto3', + serialized_options=b'\n\021io.pinecone.protoP\001Z/github.com/pinecone-io/new-go-pinecone/pinecone\222A\366\002\022K\n\014Pinecone API\";\n\017Pinecone.io Ops\022\023https://pinecone.io\032\023support@pinecone.io\0329{index_name}-{project_name}.svc.{environment}.pinecone.io*\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', + create_key=_descriptor._internal_create_key, + serialized_pb=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\"~\n\x0cSparseValues\x12\x35\n\x07indices\x18\x01 \x03(\rB$\x92\x41\x1eJ\x16[1, 312, 822, 14, 980]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12\x37\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\xe0\x41\x02\"\xfd\x01\n\x06Vector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\x02\x12G\n\x06values\x18\x02 \x03(\x02\x42\x37\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\xe0\x41\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}\"\x93\x02\n\x0cScoredVector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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}\"d\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x0c\x92\x41\x06x\xe8\x07\x80\x01\x01\xe0\x41\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\"h\n\x0c\x46\x65tchRequest\x12+\n\x03ids\x18\x01 \x03(\tB\x1e\x92\x41\x18J\x10[\"id-0\", \"id-1\"]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13\"example-namespace\"\"\xa3\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\"\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\"\xd0\x02\n\x0bQueryVector\x12G\n\x06values\x18\x01 \x03(\x02\x42\x37\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\xe0\x41\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}}\"\xfa\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\x1c\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\xe0\x41\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\"\"l\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\"\xb2\x02\n\rUpdateRequest\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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\xbd\x05\n\rVectorService\x12\x63\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/upsert:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06upsert\x12v\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"K\x82\xd3\xe4\x93\x02\'\"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x92\x41\x1b\n\x11Vector Operations*\x06\x64\x65lete\x12[\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse\"3\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x92\x41\x1a\n\x11Vector Operations*\x05\x66\x65tch\x12V\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse\".\x82\xd3\xe4\x93\x02\x0b\"\x06/query:\x01*\x92\x41\x1a\n\x11Vector Operations*\x05query\x12\x63\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/update:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06update\x12\xb4\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse\"e\x82\xd3\xe4\x93\x02\x33\"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_stats\x92\x41)\n\x11Vector Operations*\x14\x64\x65scribe_index_statsB\xc0\x03\n\x11io.pinecone.protoP\x01Z/github.com/pinecone-io/new-go-pinecone/pinecone\x92\x41\xf6\x02\x12K\n\x0cPinecone API\";\n\x0fPinecone.io Ops\x12\x13https://pinecone.io\x1a\x13support@pinecone.io\x1a\x39{index_name}-{project_name}.svc.{environment}.pinecone.io*\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' + , + dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_api_dot_field__behavior__pb2.DESCRIPTOR,protoc__gen__openapiv2_dot_options_dot_annotations__pb2.DESCRIPTOR,]) + + _SPARSEVALUES = _descriptor.Descriptor( - name="SparseValues", - full_name="SparseValues", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="indices", - full_name="SparseValues.indices", - index=0, - number=1, - type=13, - cpp_type=3, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\036J\026[1, 312, 822, 14, 980]x\350\007\200\001\001\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="values", - full_name="SparseValues.values", - index=1, - number=2, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A!J\031[0.1, 0.2, 0.3, 0.4, 0.5]x\350\007\200\001\001\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=165, - serialized_end=291, + name='SparseValues', + full_name='SparseValues', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='indices', full_name='SparseValues.indices', index=0, + number=1, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\036J\026[1, 312, 822, 14, 980]x\350\007\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='values', full_name='SparseValues.values', index=1, + number=2, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A!J\031[0.1, 0.2, 0.3, 0.4, 0.5]x\350\007\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=165, + serialized_end=291, ) _VECTOR = _descriptor.Descriptor( - name="Vector", - full_name="Vector", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="id", - full_name="Vector.id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\340A\002', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="values", - full_name="Vector.values", - index=1, - number=2, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - 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\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sparse_values", - full_name="Vector.sparse_values", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="Vector.metadata", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A(J&{"genre": "documentary", "year": 2019}', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=294, - serialized_end=547, + name='Vector', + full_name='Vector', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='id', full_name='Vector.id', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\032J\022\"example-vector-1\"x\200\004\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='values', full_name='Vector.values', index=1, + number=2, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + 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\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='sparse_values', full_name='Vector.sparse_values', index=2, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='metadata', full_name='Vector.metadata', index=3, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A(J&{\"genre\": \"documentary\", \"year\": 2019}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=294, + serialized_end=547, ) _SCOREDVECTOR = _descriptor.Descriptor( - name="ScoredVector", - full_name="ScoredVector", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="id", - full_name="ScoredVector.id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\340A\002', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="ScoredVector.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\006J\0040.08", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="values", - full_name="ScoredVector.values", - index=2, - number=3, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A*J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sparse_values", - full_name="ScoredVector.sparse_values", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="ScoredVector.metadata", - index=4, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A(J&{"genre": "documentary", "year": 2019}', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=550, - serialized_end=825, + name='ScoredVector', + full_name='ScoredVector', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='id', full_name='ScoredVector.id', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\032J\022\"example-vector-1\"x\200\004\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='score', full_name='ScoredVector.score', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\006J\0040.08', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='values', full_name='ScoredVector.values', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A*J([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='sparse_values', full_name='ScoredVector.sparse_values', index=3, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='metadata', full_name='ScoredVector.metadata', index=4, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A(J&{\"genre\": \"documentary\", \"year\": 2019}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=550, + serialized_end=825, ) _UPSERTREQUEST = _descriptor.Descriptor( - name="UpsertRequest", - full_name="UpsertRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vectors", - full_name="UpsertRequest.vectors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\006x\350\007\200\001\001\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="UpsertRequest.namespace", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=827, - serialized_end=927, + name='UpsertRequest', + full_name='UpsertRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='vectors', full_name='UpsertRequest.vectors', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\006x\350\007\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='UpsertRequest.namespace', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=827, + serialized_end=927, ) _UPSERTRESPONSE = _descriptor.Descriptor( - name="UpsertResponse", - full_name="UpsertResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="upserted_count", - full_name="UpsertResponse.upserted_count", - index=0, - number=1, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\004J\00210", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=929, - serialized_end=978, + name='UpsertResponse', + full_name='UpsertResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='upserted_count', full_name='UpsertResponse.upserted_count', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\004J\00210', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=929, + serialized_end=978, ) _DELETEREQUEST = _descriptor.Descriptor( - name="DeleteRequest", - full_name="DeleteRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="ids", - full_name="DeleteRequest.ids", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\030J\020["id-0", "id-1"]x\350\007\200\001\001', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="delete_all", - full_name="DeleteRequest.delete_all", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\016:\005falseJ\005false", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="DeleteRequest.namespace", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="DeleteRequest.filter", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=981, - serialized_end=1163, + name='DeleteRequest', + full_name='DeleteRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='ids', full_name='DeleteRequest.ids', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\030J\020[\"id-0\", \"id-1\"]x\350\007\200\001\001', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='delete_all', full_name='DeleteRequest.delete_all', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\016:\005falseJ\005false', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='DeleteRequest.namespace', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='filter', full_name='DeleteRequest.filter', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=981, + serialized_end=1163, ) _DELETERESPONSE = _descriptor.Descriptor( - name="DeleteResponse", - full_name="DeleteResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1165, - serialized_end=1181, + name='DeleteResponse', + full_name='DeleteResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1165, + serialized_end=1181, ) _FETCHREQUEST = _descriptor.Descriptor( - name="FetchRequest", - full_name="FetchRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="ids", - full_name="FetchRequest.ids", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\030J\020["id-0", "id-1"]x\350\007\200\001\001\340A\002', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="FetchRequest.namespace", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1183, - serialized_end=1287, + name='FetchRequest', + full_name='FetchRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='ids', full_name='FetchRequest.ids', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\030J\020[\"id-0\", \"id-1\"]x\350\007\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='FetchRequest.namespace', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1183, + serialized_end=1287, ) _FETCHRESPONSE_VECTORSENTRY = _descriptor.Descriptor( - name="VectorsEntry", - full_name="FetchResponse.VectorsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="FetchResponse.VectorsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="FetchResponse.VectorsEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1398, - serialized_end=1453, + name='VectorsEntry', + full_name='FetchResponse.VectorsEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='FetchResponse.VectorsEntry.key', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='value', full_name='FetchResponse.VectorsEntry.value', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=b'8\001', + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1398, + serialized_end=1453, ) _FETCHRESPONSE = _descriptor.Descriptor( - name="FetchResponse", - full_name="FetchResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vectors", - full_name="FetchResponse.vectors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="FetchResponse.namespace", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _FETCHRESPONSE_VECTORSENTRY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1290, - serialized_end=1453, + name='FetchResponse', + full_name='FetchResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='vectors', full_name='FetchResponse.vectors', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='FetchResponse.namespace', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_FETCHRESPONSE_VECTORSENTRY, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1290, + serialized_end=1453, ) _QUERYVECTOR = _descriptor.Descriptor( - name="QueryVector", - full_name="QueryVector", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="values", - full_name="QueryVector.values", - index=0, - number=1, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - 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\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sparse_values", - full_name="QueryVector.sparse_values", - index=1, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="top_k", - full_name="QueryVector.top_k", - index=2, - number=2, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="QueryVector.namespace", - index=3, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="QueryVector.filter", - index=4, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222AOJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1456, - serialized_end=1792, + name='QueryVector', + full_name='QueryVector', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='values', full_name='QueryVector.values', index=0, + number=1, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + 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\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='sparse_values', full_name='QueryVector.sparse_values', index=1, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='top_k', full_name='QueryVector.top_k', index=2, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='QueryVector.namespace', index=3, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='filter', full_name='QueryVector.filter', index=4, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222AOJM{\"genre\": {\"$in\": [\"comedy\", \"documentary\", \"drama\"]}, \"year\": {\"$eq\": 2019}}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1456, + serialized_end=1792, ) _QUERYREQUEST = _descriptor.Descriptor( - name="QueryRequest", - full_name="QueryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="QueryRequest.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="top_k", - full_name="QueryRequest.top_k", - index=1, - number=2, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="QueryRequest.filter", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222AOJM{"genre": {"$in": ["comedy", "documentary", "drama"]}, "year": {"$eq": 2019}}', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="include_values", - full_name="QueryRequest.include_values", - index=3, - number=4, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\r:\005falseJ\004true", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="include_metadata", - full_name="QueryRequest.include_metadata", - index=4, - number=5, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\r:\005falseJ\004true", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="queries", - full_name="QueryRequest.queries", - index=5, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\030\001\222A\005x\n\200\001\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="vector", - full_name="QueryRequest.vector", - index=6, - number=7, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - 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", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sparse_vector", - full_name="QueryRequest.sparse_vector", - index=7, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="id", - full_name="QueryRequest.id", - index=8, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\027J\022"example-vector-1"x\200\004', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1795, - serialized_end=2301, + name='QueryRequest', + full_name='QueryRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='namespace', full_name='QueryRequest.namespace', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='top_k', full_name='QueryRequest.top_k', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\026J\00210Y\000\000\000\000\000\210\303@i\000\000\000\000\000\000\360?\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='filter', full_name='QueryRequest.filter', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222AOJM{\"genre\": {\"$in\": [\"comedy\", \"documentary\", \"drama\"]}, \"year\": {\"$eq\": 2019}}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='include_values', full_name='QueryRequest.include_values', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\r:\005falseJ\004true', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='include_metadata', full_name='QueryRequest.include_metadata', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\r:\005falseJ\004true', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='queries', full_name='QueryRequest.queries', index=5, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001\222A\005x\n\200\001\001', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='vector', full_name='QueryRequest.vector', index=6, + number=7, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + 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', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='sparse_vector', full_name='QueryRequest.sparse_vector', index=7, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='id', full_name='QueryRequest.id', index=8, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\027J\022\"example-vector-1\"x\200\004', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1795, + serialized_end=2301, ) _SINGLEQUERYRESULTS = _descriptor.Descriptor( - name="SingleQueryResults", - full_name="SingleQueryResults", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matches", - full_name="SingleQueryResults.matches", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="SingleQueryResults.namespace", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2303, - serialized_end=2400, + name='SingleQueryResults', + full_name='SingleQueryResults', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='matches', full_name='SingleQueryResults.matches', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='SingleQueryResults.namespace', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2303, + serialized_end=2400, ) _QUERYRESPONSE = _descriptor.Descriptor( - name="QueryResponse", - full_name="QueryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="results", - full_name="QueryResponse.results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\030\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="matches", - full_name="QueryResponse.matches", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="QueryResponse.namespace", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2402, - serialized_end=2510, + name='QueryResponse', + full_name='QueryResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='results', full_name='QueryResponse.results', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='matches', full_name='QueryResponse.matches', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='QueryResponse.namespace', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2402, + serialized_end=2510, ) _UPDATEREQUEST = _descriptor.Descriptor( - name="UpdateRequest", - full_name="UpdateRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="id", - full_name="UpdateRequest.id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\032J\022"example-vector-1"x\200\004\200\001\001\340A\002', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="values", - full_name="UpdateRequest.values", - index=1, - number=2, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - 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", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sparse_values", - full_name="UpdateRequest.sparse_values", - index=2, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="set_metadata", - full_name="UpdateRequest.set_metadata", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A(J&{"genre": "documentary", "year": 2019}', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace", - full_name="UpdateRequest.namespace", - index=4, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\222A\025J\023"example-namespace"', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2513, - serialized_end=2819, + name='UpdateRequest', + full_name='UpdateRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='id', full_name='UpdateRequest.id', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\032J\022\"example-vector-1\"x\200\004\200\001\001\340A\002', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='values', full_name='UpdateRequest.values', index=1, + number=2, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + 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', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='sparse_values', full_name='UpdateRequest.sparse_values', index=2, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='set_metadata', full_name='UpdateRequest.set_metadata', index=3, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A(J&{\"genre\": \"documentary\", \"year\": 2019}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='namespace', full_name='UpdateRequest.namespace', index=4, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2513, + serialized_end=2819, ) _UPDATERESPONSE = _descriptor.Descriptor( - name="UpdateResponse", - full_name="UpdateResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2821, - serialized_end=2837, + name='UpdateResponse', + full_name='UpdateResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2821, + serialized_end=2837, ) _DESCRIBEINDEXSTATSREQUEST = _descriptor.Descriptor( - name="DescribeIndexStatsRequest", - full_name="DescribeIndexStatsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="filter", - full_name="DescribeIndexStatsRequest.filter", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2839, - serialized_end=2907, + name='DescribeIndexStatsRequest', + full_name='DescribeIndexStatsRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='filter', full_name='DescribeIndexStatsRequest.filter', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2839, + serialized_end=2907, ) _NAMESPACESUMMARY = _descriptor.Descriptor( - name="NamespaceSummary", - full_name="NamespaceSummary", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vector_count", - full_name="NamespaceSummary.vector_count", - index=0, - number=1, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\007J\00550000", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2909, - serialized_end=2961, + name='NamespaceSummary', + full_name='NamespaceSummary', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='vector_count', full_name='NamespaceSummary.vector_count', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\007J\00550000', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2909, + serialized_end=2961, ) _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY = _descriptor.Descriptor( - name="NamespacesEntry", - full_name="DescribeIndexStatsResponse.NamespacesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="DescribeIndexStatsResponse.NamespacesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="DescribeIndexStatsResponse.NamespacesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3163, - serialized_end=3231, + name='NamespacesEntry', + full_name='DescribeIndexStatsResponse.NamespacesEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='DescribeIndexStatsResponse.NamespacesEntry.key', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='value', full_name='DescribeIndexStatsResponse.NamespacesEntry.value', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=b'8\001', + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3163, + serialized_end=3231, ) _DESCRIBEINDEXSTATSRESPONSE = _descriptor.Descriptor( - name="DescribeIndexStatsResponse", - full_name="DescribeIndexStatsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespaces", - full_name="DescribeIndexStatsResponse.namespaces", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dimension", - full_name="DescribeIndexStatsResponse.dimension", - index=1, - number=2, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\006J\0041024", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_fullness", - full_name="DescribeIndexStatsResponse.index_fullness", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\005J\0030.4", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_vector_count", - full_name="DescribeIndexStatsResponse.total_vector_count", - index=3, - number=4, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\222A\007J\00580000", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, - ], - enum_types=[], - serialized_options=b'\222A\210\0012\205\001{"namespaces": {"": {"vectorCount": 50000}, "example-namespace-2": {"vectorCount": 30000}}, "dimension": 1024, "index_fullness": 0.4}', - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2964, - serialized_end=3374, + name='DescribeIndexStatsResponse', + full_name='DescribeIndexStatsResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='namespaces', full_name='DescribeIndexStatsResponse.namespaces', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='dimension', full_name='DescribeIndexStatsResponse.dimension', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\006J\0041024', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='index_fullness', full_name='DescribeIndexStatsResponse.index_fullness', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\005J\0030.4', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='total_vector_count', full_name='DescribeIndexStatsResponse.total_vector_count', index=3, + number=4, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\007J\00580000', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, ], + enum_types=[ + ], + serialized_options=b'\222A\210\0012\205\001{\"namespaces\": {\"\": {\"vectorCount\": 50000}, \"example-namespace-2\": {\"vectorCount\": 30000}}, \"dimension\": 1024, \"index_fullness\": 0.4}', + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2964, + serialized_end=3374, ) -_VECTOR.fields_by_name["sparse_values"].message_type = _SPARSEVALUES -_VECTOR.fields_by_name["metadata"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_SCOREDVECTOR.fields_by_name["sparse_values"].message_type = _SPARSEVALUES -_SCOREDVECTOR.fields_by_name["metadata"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_UPSERTREQUEST.fields_by_name["vectors"].message_type = _VECTOR -_DELETEREQUEST.fields_by_name["filter"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_FETCHRESPONSE_VECTORSENTRY.fields_by_name["value"].message_type = _VECTOR +_VECTOR.fields_by_name['sparse_values'].message_type = _SPARSEVALUES +_VECTOR.fields_by_name['metadata'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_SCOREDVECTOR.fields_by_name['sparse_values'].message_type = _SPARSEVALUES +_SCOREDVECTOR.fields_by_name['metadata'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_UPSERTREQUEST.fields_by_name['vectors'].message_type = _VECTOR +_DELETEREQUEST.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_FETCHRESPONSE_VECTORSENTRY.fields_by_name['value'].message_type = _VECTOR _FETCHRESPONSE_VECTORSENTRY.containing_type = _FETCHRESPONSE -_FETCHRESPONSE.fields_by_name["vectors"].message_type = _FETCHRESPONSE_VECTORSENTRY -_QUERYVECTOR.fields_by_name["sparse_values"].message_type = _SPARSEVALUES -_QUERYVECTOR.fields_by_name["filter"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_QUERYREQUEST.fields_by_name["filter"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_QUERYREQUEST.fields_by_name["queries"].message_type = _QUERYVECTOR -_QUERYREQUEST.fields_by_name["sparse_vector"].message_type = _SPARSEVALUES -_SINGLEQUERYRESULTS.fields_by_name["matches"].message_type = _SCOREDVECTOR -_QUERYRESPONSE.fields_by_name["results"].message_type = _SINGLEQUERYRESULTS -_QUERYRESPONSE.fields_by_name["matches"].message_type = _SCOREDVECTOR -_UPDATEREQUEST.fields_by_name["sparse_values"].message_type = _SPARSEVALUES -_UPDATEREQUEST.fields_by_name["set_metadata"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_DESCRIBEINDEXSTATSREQUEST.fields_by_name["filter"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY.fields_by_name["value"].message_type = _NAMESPACESUMMARY +_FETCHRESPONSE.fields_by_name['vectors'].message_type = _FETCHRESPONSE_VECTORSENTRY +_QUERYVECTOR.fields_by_name['sparse_values'].message_type = _SPARSEVALUES +_QUERYVECTOR.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_QUERYREQUEST.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_QUERYREQUEST.fields_by_name['queries'].message_type = _QUERYVECTOR +_QUERYREQUEST.fields_by_name['sparse_vector'].message_type = _SPARSEVALUES +_SINGLEQUERYRESULTS.fields_by_name['matches'].message_type = _SCOREDVECTOR +_QUERYRESPONSE.fields_by_name['results'].message_type = _SINGLEQUERYRESULTS +_QUERYRESPONSE.fields_by_name['matches'].message_type = _SCOREDVECTOR +_UPDATEREQUEST.fields_by_name['sparse_values'].message_type = _SPARSEVALUES +_UPDATEREQUEST.fields_by_name['set_metadata'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_DESCRIBEINDEXSTATSREQUEST.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY.fields_by_name['value'].message_type = _NAMESPACESUMMARY _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY.containing_type = _DESCRIBEINDEXSTATSRESPONSE -_DESCRIBEINDEXSTATSRESPONSE.fields_by_name["namespaces"].message_type = _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY -DESCRIPTOR.message_types_by_name["SparseValues"] = _SPARSEVALUES -DESCRIPTOR.message_types_by_name["Vector"] = _VECTOR -DESCRIPTOR.message_types_by_name["ScoredVector"] = _SCOREDVECTOR -DESCRIPTOR.message_types_by_name["UpsertRequest"] = _UPSERTREQUEST -DESCRIPTOR.message_types_by_name["UpsertResponse"] = _UPSERTRESPONSE -DESCRIPTOR.message_types_by_name["DeleteRequest"] = _DELETEREQUEST -DESCRIPTOR.message_types_by_name["DeleteResponse"] = _DELETERESPONSE -DESCRIPTOR.message_types_by_name["FetchRequest"] = _FETCHREQUEST -DESCRIPTOR.message_types_by_name["FetchResponse"] = _FETCHRESPONSE -DESCRIPTOR.message_types_by_name["QueryVector"] = _QUERYVECTOR -DESCRIPTOR.message_types_by_name["QueryRequest"] = _QUERYREQUEST -DESCRIPTOR.message_types_by_name["SingleQueryResults"] = _SINGLEQUERYRESULTS -DESCRIPTOR.message_types_by_name["QueryResponse"] = _QUERYRESPONSE -DESCRIPTOR.message_types_by_name["UpdateRequest"] = _UPDATEREQUEST -DESCRIPTOR.message_types_by_name["UpdateResponse"] = _UPDATERESPONSE -DESCRIPTOR.message_types_by_name["DescribeIndexStatsRequest"] = _DESCRIBEINDEXSTATSREQUEST -DESCRIPTOR.message_types_by_name["NamespaceSummary"] = _NAMESPACESUMMARY -DESCRIPTOR.message_types_by_name["DescribeIndexStatsResponse"] = _DESCRIBEINDEXSTATSRESPONSE +_DESCRIBEINDEXSTATSRESPONSE.fields_by_name['namespaces'].message_type = _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY +DESCRIPTOR.message_types_by_name['SparseValues'] = _SPARSEVALUES +DESCRIPTOR.message_types_by_name['Vector'] = _VECTOR +DESCRIPTOR.message_types_by_name['ScoredVector'] = _SCOREDVECTOR +DESCRIPTOR.message_types_by_name['UpsertRequest'] = _UPSERTREQUEST +DESCRIPTOR.message_types_by_name['UpsertResponse'] = _UPSERTRESPONSE +DESCRIPTOR.message_types_by_name['DeleteRequest'] = _DELETEREQUEST +DESCRIPTOR.message_types_by_name['DeleteResponse'] = _DELETERESPONSE +DESCRIPTOR.message_types_by_name['FetchRequest'] = _FETCHREQUEST +DESCRIPTOR.message_types_by_name['FetchResponse'] = _FETCHRESPONSE +DESCRIPTOR.message_types_by_name['QueryVector'] = _QUERYVECTOR +DESCRIPTOR.message_types_by_name['QueryRequest'] = _QUERYREQUEST +DESCRIPTOR.message_types_by_name['SingleQueryResults'] = _SINGLEQUERYRESULTS +DESCRIPTOR.message_types_by_name['QueryResponse'] = _QUERYRESPONSE +DESCRIPTOR.message_types_by_name['UpdateRequest'] = _UPDATEREQUEST +DESCRIPTOR.message_types_by_name['UpdateResponse'] = _UPDATERESPONSE +DESCRIPTOR.message_types_by_name['DescribeIndexStatsRequest'] = _DESCRIBEINDEXSTATSREQUEST +DESCRIPTOR.message_types_by_name['NamespaceSummary'] = _NAMESPACESUMMARY +DESCRIPTOR.message_types_by_name['DescribeIndexStatsResponse'] = _DESCRIBEINDEXSTATSRESPONSE _sym_db.RegisterFileDescriptor(DESCRIPTOR) -SparseValues = _reflection.GeneratedProtocolMessageType( - "SparseValues", - (_message.Message,), - { - "DESCRIPTOR": _SPARSEVALUES, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:SparseValues) - }, -) +SparseValues = _reflection.GeneratedProtocolMessageType('SparseValues', (_message.Message,), { + 'DESCRIPTOR' : _SPARSEVALUES, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:SparseValues) + }) _sym_db.RegisterMessage(SparseValues) -Vector = _reflection.GeneratedProtocolMessageType( - "Vector", - (_message.Message,), - { - "DESCRIPTOR": _VECTOR, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:Vector) - }, -) +Vector = _reflection.GeneratedProtocolMessageType('Vector', (_message.Message,), { + 'DESCRIPTOR' : _VECTOR, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:Vector) + }) _sym_db.RegisterMessage(Vector) -ScoredVector = _reflection.GeneratedProtocolMessageType( - "ScoredVector", - (_message.Message,), - { - "DESCRIPTOR": _SCOREDVECTOR, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:ScoredVector) - }, -) +ScoredVector = _reflection.GeneratedProtocolMessageType('ScoredVector', (_message.Message,), { + 'DESCRIPTOR' : _SCOREDVECTOR, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:ScoredVector) + }) _sym_db.RegisterMessage(ScoredVector) -UpsertRequest = _reflection.GeneratedProtocolMessageType( - "UpsertRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPSERTREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:UpsertRequest) - }, -) +UpsertRequest = _reflection.GeneratedProtocolMessageType('UpsertRequest', (_message.Message,), { + 'DESCRIPTOR' : _UPSERTREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:UpsertRequest) + }) _sym_db.RegisterMessage(UpsertRequest) -UpsertResponse = _reflection.GeneratedProtocolMessageType( - "UpsertResponse", - (_message.Message,), - { - "DESCRIPTOR": _UPSERTRESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:UpsertResponse) - }, -) +UpsertResponse = _reflection.GeneratedProtocolMessageType('UpsertResponse', (_message.Message,), { + 'DESCRIPTOR' : _UPSERTRESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:UpsertResponse) + }) _sym_db.RegisterMessage(UpsertResponse) -DeleteRequest = _reflection.GeneratedProtocolMessageType( - "DeleteRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:DeleteRequest) - }, -) +DeleteRequest = _reflection.GeneratedProtocolMessageType('DeleteRequest', (_message.Message,), { + 'DESCRIPTOR' : _DELETEREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:DeleteRequest) + }) _sym_db.RegisterMessage(DeleteRequest) -DeleteResponse = _reflection.GeneratedProtocolMessageType( - "DeleteResponse", - (_message.Message,), - { - "DESCRIPTOR": _DELETERESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:DeleteResponse) - }, -) +DeleteResponse = _reflection.GeneratedProtocolMessageType('DeleteResponse', (_message.Message,), { + 'DESCRIPTOR' : _DELETERESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:DeleteResponse) + }) _sym_db.RegisterMessage(DeleteResponse) -FetchRequest = _reflection.GeneratedProtocolMessageType( - "FetchRequest", - (_message.Message,), - { - "DESCRIPTOR": _FETCHREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:FetchRequest) - }, -) +FetchRequest = _reflection.GeneratedProtocolMessageType('FetchRequest', (_message.Message,), { + 'DESCRIPTOR' : _FETCHREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:FetchRequest) + }) _sym_db.RegisterMessage(FetchRequest) -FetchResponse = _reflection.GeneratedProtocolMessageType( - "FetchResponse", - (_message.Message,), - { - "VectorsEntry": _reflection.GeneratedProtocolMessageType( - "VectorsEntry", - (_message.Message,), - { - "DESCRIPTOR": _FETCHRESPONSE_VECTORSENTRY, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:FetchResponse.VectorsEntry) - }, - ), - "DESCRIPTOR": _FETCHRESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:FetchResponse) - }, -) +FetchResponse = _reflection.GeneratedProtocolMessageType('FetchResponse', (_message.Message,), { + + 'VectorsEntry' : _reflection.GeneratedProtocolMessageType('VectorsEntry', (_message.Message,), { + 'DESCRIPTOR' : _FETCHRESPONSE_VECTORSENTRY, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:FetchResponse.VectorsEntry) + }) + , + 'DESCRIPTOR' : _FETCHRESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:FetchResponse) + }) _sym_db.RegisterMessage(FetchResponse) _sym_db.RegisterMessage(FetchResponse.VectorsEntry) -QueryVector = _reflection.GeneratedProtocolMessageType( - "QueryVector", - (_message.Message,), - { - "DESCRIPTOR": _QUERYVECTOR, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:QueryVector) - }, -) +QueryVector = _reflection.GeneratedProtocolMessageType('QueryVector', (_message.Message,), { + 'DESCRIPTOR' : _QUERYVECTOR, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:QueryVector) + }) _sym_db.RegisterMessage(QueryVector) -QueryRequest = _reflection.GeneratedProtocolMessageType( - "QueryRequest", - (_message.Message,), - { - "DESCRIPTOR": _QUERYREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:QueryRequest) - }, -) +QueryRequest = _reflection.GeneratedProtocolMessageType('QueryRequest', (_message.Message,), { + 'DESCRIPTOR' : _QUERYREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:QueryRequest) + }) _sym_db.RegisterMessage(QueryRequest) -SingleQueryResults = _reflection.GeneratedProtocolMessageType( - "SingleQueryResults", - (_message.Message,), - { - "DESCRIPTOR": _SINGLEQUERYRESULTS, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:SingleQueryResults) - }, -) +SingleQueryResults = _reflection.GeneratedProtocolMessageType('SingleQueryResults', (_message.Message,), { + 'DESCRIPTOR' : _SINGLEQUERYRESULTS, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:SingleQueryResults) + }) _sym_db.RegisterMessage(SingleQueryResults) -QueryResponse = _reflection.GeneratedProtocolMessageType( - "QueryResponse", - (_message.Message,), - { - "DESCRIPTOR": _QUERYRESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:QueryResponse) - }, -) +QueryResponse = _reflection.GeneratedProtocolMessageType('QueryResponse', (_message.Message,), { + 'DESCRIPTOR' : _QUERYRESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:QueryResponse) + }) _sym_db.RegisterMessage(QueryResponse) -UpdateRequest = _reflection.GeneratedProtocolMessageType( - "UpdateRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:UpdateRequest) - }, -) +UpdateRequest = _reflection.GeneratedProtocolMessageType('UpdateRequest', (_message.Message,), { + 'DESCRIPTOR' : _UPDATEREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:UpdateRequest) + }) _sym_db.RegisterMessage(UpdateRequest) -UpdateResponse = _reflection.GeneratedProtocolMessageType( - "UpdateResponse", - (_message.Message,), - { - "DESCRIPTOR": _UPDATERESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:UpdateResponse) - }, -) +UpdateResponse = _reflection.GeneratedProtocolMessageType('UpdateResponse', (_message.Message,), { + 'DESCRIPTOR' : _UPDATERESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:UpdateResponse) + }) _sym_db.RegisterMessage(UpdateResponse) -DescribeIndexStatsRequest = _reflection.GeneratedProtocolMessageType( - "DescribeIndexStatsRequest", - (_message.Message,), - { - "DESCRIPTOR": _DESCRIBEINDEXSTATSREQUEST, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:DescribeIndexStatsRequest) - }, -) +DescribeIndexStatsRequest = _reflection.GeneratedProtocolMessageType('DescribeIndexStatsRequest', (_message.Message,), { + 'DESCRIPTOR' : _DESCRIBEINDEXSTATSREQUEST, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:DescribeIndexStatsRequest) + }) _sym_db.RegisterMessage(DescribeIndexStatsRequest) -NamespaceSummary = _reflection.GeneratedProtocolMessageType( - "NamespaceSummary", - (_message.Message,), - { - "DESCRIPTOR": _NAMESPACESUMMARY, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:NamespaceSummary) - }, -) +NamespaceSummary = _reflection.GeneratedProtocolMessageType('NamespaceSummary', (_message.Message,), { + 'DESCRIPTOR' : _NAMESPACESUMMARY, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:NamespaceSummary) + }) _sym_db.RegisterMessage(NamespaceSummary) -DescribeIndexStatsResponse = _reflection.GeneratedProtocolMessageType( - "DescribeIndexStatsResponse", - (_message.Message,), - { - "NamespacesEntry": _reflection.GeneratedProtocolMessageType( - "NamespacesEntry", - (_message.Message,), - { - "DESCRIPTOR": _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:DescribeIndexStatsResponse.NamespacesEntry) - }, - ), - "DESCRIPTOR": _DESCRIBEINDEXSTATSRESPONSE, - "__module__": "vector_service_pb2" - # @@protoc_insertion_point(class_scope:DescribeIndexStatsResponse) - }, -) +DescribeIndexStatsResponse = _reflection.GeneratedProtocolMessageType('DescribeIndexStatsResponse', (_message.Message,), { + + 'NamespacesEntry' : _reflection.GeneratedProtocolMessageType('NamespacesEntry', (_message.Message,), { + 'DESCRIPTOR' : _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:DescribeIndexStatsResponse.NamespacesEntry) + }) + , + 'DESCRIPTOR' : _DESCRIBEINDEXSTATSRESPONSE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:DescribeIndexStatsResponse) + }) _sym_db.RegisterMessage(DescribeIndexStatsResponse) _sym_db.RegisterMessage(DescribeIndexStatsResponse.NamespacesEntry) DESCRIPTOR._options = None -_SPARSEVALUES.fields_by_name["indices"]._options = None -_SPARSEVALUES.fields_by_name["values"]._options = None -_VECTOR.fields_by_name["id"]._options = None -_VECTOR.fields_by_name["values"]._options = None -_VECTOR.fields_by_name["metadata"]._options = None -_SCOREDVECTOR.fields_by_name["id"]._options = None -_SCOREDVECTOR.fields_by_name["score"]._options = None -_SCOREDVECTOR.fields_by_name["values"]._options = None -_SCOREDVECTOR.fields_by_name["metadata"]._options = None -_UPSERTREQUEST.fields_by_name["vectors"]._options = None -_UPSERTREQUEST.fields_by_name["namespace"]._options = None -_UPSERTRESPONSE.fields_by_name["upserted_count"]._options = None -_DELETEREQUEST.fields_by_name["ids"]._options = None -_DELETEREQUEST.fields_by_name["delete_all"]._options = None -_DELETEREQUEST.fields_by_name["namespace"]._options = None -_FETCHREQUEST.fields_by_name["ids"]._options = None -_FETCHREQUEST.fields_by_name["namespace"]._options = None +_SPARSEVALUES.fields_by_name['indices']._options = None +_SPARSEVALUES.fields_by_name['values']._options = None +_VECTOR.fields_by_name['id']._options = None +_VECTOR.fields_by_name['values']._options = None +_VECTOR.fields_by_name['metadata']._options = None +_SCOREDVECTOR.fields_by_name['id']._options = None +_SCOREDVECTOR.fields_by_name['score']._options = None +_SCOREDVECTOR.fields_by_name['values']._options = None +_SCOREDVECTOR.fields_by_name['metadata']._options = None +_UPSERTREQUEST.fields_by_name['vectors']._options = None +_UPSERTREQUEST.fields_by_name['namespace']._options = None +_UPSERTRESPONSE.fields_by_name['upserted_count']._options = None +_DELETEREQUEST.fields_by_name['ids']._options = None +_DELETEREQUEST.fields_by_name['delete_all']._options = None +_DELETEREQUEST.fields_by_name['namespace']._options = None +_FETCHREQUEST.fields_by_name['ids']._options = None +_FETCHREQUEST.fields_by_name['namespace']._options = None _FETCHRESPONSE_VECTORSENTRY._options = None -_FETCHRESPONSE.fields_by_name["namespace"]._options = None -_QUERYVECTOR.fields_by_name["values"]._options = None -_QUERYVECTOR.fields_by_name["top_k"]._options = None -_QUERYVECTOR.fields_by_name["namespace"]._options = None -_QUERYVECTOR.fields_by_name["filter"]._options = None -_QUERYREQUEST.fields_by_name["namespace"]._options = None -_QUERYREQUEST.fields_by_name["top_k"]._options = None -_QUERYREQUEST.fields_by_name["filter"]._options = None -_QUERYREQUEST.fields_by_name["include_values"]._options = None -_QUERYREQUEST.fields_by_name["include_metadata"]._options = None -_QUERYREQUEST.fields_by_name["queries"]._options = None -_QUERYREQUEST.fields_by_name["vector"]._options = None -_QUERYREQUEST.fields_by_name["id"]._options = None -_SINGLEQUERYRESULTS.fields_by_name["namespace"]._options = None -_QUERYRESPONSE.fields_by_name["results"]._options = None -_UPDATEREQUEST.fields_by_name["id"]._options = None -_UPDATEREQUEST.fields_by_name["values"]._options = None -_UPDATEREQUEST.fields_by_name["set_metadata"]._options = None -_UPDATEREQUEST.fields_by_name["namespace"]._options = None -_NAMESPACESUMMARY.fields_by_name["vector_count"]._options = None +_FETCHRESPONSE.fields_by_name['namespace']._options = None +_QUERYVECTOR.fields_by_name['values']._options = None +_QUERYVECTOR.fields_by_name['top_k']._options = None +_QUERYVECTOR.fields_by_name['namespace']._options = None +_QUERYVECTOR.fields_by_name['filter']._options = None +_QUERYREQUEST.fields_by_name['namespace']._options = None +_QUERYREQUEST.fields_by_name['top_k']._options = None +_QUERYREQUEST.fields_by_name['filter']._options = None +_QUERYREQUEST.fields_by_name['include_values']._options = None +_QUERYREQUEST.fields_by_name['include_metadata']._options = None +_QUERYREQUEST.fields_by_name['queries']._options = None +_QUERYREQUEST.fields_by_name['vector']._options = None +_QUERYREQUEST.fields_by_name['id']._options = None +_SINGLEQUERYRESULTS.fields_by_name['namespace']._options = None +_QUERYRESPONSE.fields_by_name['results']._options = None +_UPDATEREQUEST.fields_by_name['id']._options = None +_UPDATEREQUEST.fields_by_name['values']._options = None +_UPDATEREQUEST.fields_by_name['set_metadata']._options = None +_UPDATEREQUEST.fields_by_name['namespace']._options = None +_NAMESPACESUMMARY.fields_by_name['vector_count']._options = None _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY._options = None -_DESCRIBEINDEXSTATSRESPONSE.fields_by_name["dimension"]._options = None -_DESCRIBEINDEXSTATSRESPONSE.fields_by_name["index_fullness"]._options = None -_DESCRIBEINDEXSTATSRESPONSE.fields_by_name["total_vector_count"]._options = None +_DESCRIBEINDEXSTATSRESPONSE.fields_by_name['dimension']._options = None +_DESCRIBEINDEXSTATSRESPONSE.fields_by_name['index_fullness']._options = None +_DESCRIBEINDEXSTATSRESPONSE.fields_by_name['total_vector_count']._options = None _DESCRIBEINDEXSTATSRESPONSE._options = None _VECTORSERVICE = _descriptor.ServiceDescriptor( - name="VectorService", - full_name="VectorService", - file=DESCRIPTOR, + name='VectorService', + full_name='VectorService', + file=DESCRIPTOR, + index=0, + serialized_options=None, + create_key=_descriptor._internal_create_key, + serialized_start=3377, + serialized_end=4078, + methods=[ + _descriptor.MethodDescriptor( + name='Upsert', + full_name='VectorService.Upsert', index=0, - serialized_options=None, + containing_service=None, + input_type=_UPSERTREQUEST, + output_type=_UPSERTRESPONSE, + serialized_options=b'\202\323\344\223\002\024\"\017/vectors/upsert:\001*\222A\033\n\021Vector Operations*\006upsert', create_key=_descriptor._internal_create_key, - serialized_start=3377, - serialized_end=4078, - methods=[ - _descriptor.MethodDescriptor( - name="Upsert", - full_name="VectorService.Upsert", - index=0, - containing_service=None, - input_type=_UPSERTREQUEST, - output_type=_UPSERTRESPONSE, - serialized_options=b'\202\323\344\223\002\024"\017/vectors/upsert:\001*\222A\033\n\021Vector Operations*\006upsert', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Delete", - full_name="VectorService.Delete", - index=1, - containing_service=None, - input_type=_DELETEREQUEST, - output_type=_DELETERESPONSE, - serialized_options=b"\202\323\344\223\002'\"\017/vectors/delete:\001*Z\021*\017/vectors/delete\222A\033\n\021Vector Operations*\006delete", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Fetch", - full_name="VectorService.Fetch", - index=2, - containing_service=None, - input_type=_FETCHREQUEST, - output_type=_FETCHRESPONSE, - serialized_options=b"\202\323\344\223\002\020\022\016/vectors/fetch\222A\032\n\021Vector Operations*\005fetch", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Query", - full_name="VectorService.Query", - index=3, - containing_service=None, - input_type=_QUERYREQUEST, - output_type=_QUERYRESPONSE, - serialized_options=b'\202\323\344\223\002\013"\006/query:\001*\222A\032\n\021Vector Operations*\005query', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Update", - full_name="VectorService.Update", - index=4, - containing_service=None, - input_type=_UPDATEREQUEST, - output_type=_UPDATERESPONSE, - serialized_options=b'\202\323\344\223\002\024"\017/vectors/update:\001*\222A\033\n\021Vector Operations*\006update', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DescribeIndexStats", - full_name="VectorService.DescribeIndexStats", - index=5, - containing_service=None, - input_type=_DESCRIBEINDEXSTATSREQUEST, - output_type=_DESCRIBEINDEXSTATSRESPONSE, - serialized_options=b'\202\323\344\223\0023"\025/describe_index_stats:\001*Z\027\022\025/describe_index_stats\222A)\n\021Vector Operations*\024describe_index_stats', - create_key=_descriptor._internal_create_key, - ), - ], -) + ), + _descriptor.MethodDescriptor( + name='Delete', + full_name='VectorService.Delete', + index=1, + containing_service=None, + input_type=_DELETEREQUEST, + output_type=_DELETERESPONSE, + serialized_options=b'\202\323\344\223\002\'\"\017/vectors/delete:\001*Z\021*\017/vectors/delete\222A\033\n\021Vector Operations*\006delete', + create_key=_descriptor._internal_create_key, + ), + _descriptor.MethodDescriptor( + name='Fetch', + full_name='VectorService.Fetch', + index=2, + containing_service=None, + input_type=_FETCHREQUEST, + output_type=_FETCHRESPONSE, + serialized_options=b'\202\323\344\223\002\020\022\016/vectors/fetch\222A\032\n\021Vector Operations*\005fetch', + create_key=_descriptor._internal_create_key, + ), + _descriptor.MethodDescriptor( + name='Query', + full_name='VectorService.Query', + index=3, + containing_service=None, + input_type=_QUERYREQUEST, + output_type=_QUERYRESPONSE, + serialized_options=b'\202\323\344\223\002\013\"\006/query:\001*\222A\032\n\021Vector Operations*\005query', + create_key=_descriptor._internal_create_key, + ), + _descriptor.MethodDescriptor( + name='Update', + full_name='VectorService.Update', + index=4, + containing_service=None, + input_type=_UPDATEREQUEST, + output_type=_UPDATERESPONSE, + serialized_options=b'\202\323\344\223\002\024\"\017/vectors/update:\001*\222A\033\n\021Vector Operations*\006update', + create_key=_descriptor._internal_create_key, + ), + _descriptor.MethodDescriptor( + name='DescribeIndexStats', + full_name='VectorService.DescribeIndexStats', + index=5, + containing_service=None, + input_type=_DESCRIBEINDEXSTATSREQUEST, + output_type=_DESCRIBEINDEXSTATSRESPONSE, + serialized_options=b'\202\323\344\223\0023\"\025/describe_index_stats:\001*Z\027\022\025/describe_index_stats\222A)\n\021Vector Operations*\024describe_index_stats', + create_key=_descriptor._internal_create_key, + ), +]) _sym_db.RegisterServiceDescriptor(_VECTORSERVICE) -DESCRIPTOR.services_by_name["VectorService"] = _VECTORSERVICE +DESCRIPTOR.services_by_name['VectorService'] = _VECTORSERVICE # @@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 index a8c3c4d00..0c2c73f62 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.pyi +++ b/pinecone/core/grpc/protos/vector_service_pb2.pyi @@ -30,11 +30,13 @@ from typing_extensions import ( Literal as typing_extensions___Literal, ) + builtin___bool = bool builtin___bytes = bytes builtin___float = float builtin___int = int + DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ... class SparseValues(google___protobuf___message___Message): @@ -42,16 +44,12 @@ class SparseValues(google___protobuf___message___Message): indices: google___protobuf___internal___containers___RepeatedScalarFieldContainer[builtin___int] = ... values: google___protobuf___internal___containers___RepeatedScalarFieldContainer[builtin___float] = ... - def __init__( - self, + def __init__(self, *, - indices: typing___Optional[typing___Iterable[builtin___int]] = None, - values: typing___Optional[typing___Iterable[builtin___float]] = None, - ) -> None: ... - def ClearField( - self, field_name: typing_extensions___Literal["indices", b"indices", "values", b"values"] - ) -> None: ... - + indices : typing___Optional[typing___Iterable[builtin___int]] = None, + values : typing___Optional[typing___Iterable[builtin___float]] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"indices",b"indices",u"values",b"values"]) -> None: ... type___SparseValues = SparseValues class Vector(google___protobuf___message___Message): @@ -61,26 +59,19 @@ class Vector(google___protobuf___message___Message): @property def sparse_values(self) -> type___SparseValues: ... + @property def metadata(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - id: typing___Optional[typing___Text] = None, - values: typing___Optional[typing___Iterable[builtin___float]] = None, - sparse_values: typing___Optional[type___SparseValues] = None, - metadata: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - ) -> None: ... - def HasField( - self, field_name: typing_extensions___Literal["metadata", b"metadata", "sparse_values", b"sparse_values"] - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "id", b"id", "metadata", b"metadata", "sparse_values", b"sparse_values", "values", b"values" - ], - ) -> None: ... + def __init__(self, + *, + id : typing___Optional[typing___Text] = None, + values : typing___Optional[typing___Iterable[builtin___float]] = None, + sparse_values : typing___Optional[type___SparseValues] = None, + metadata : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"metadata",b"metadata",u"sparse_values",b"sparse_values"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"id",b"id",u"metadata",b"metadata",u"sparse_values",b"sparse_values",u"values",b"values"]) -> None: ... type___Vector = Vector class ScoredVector(google___protobuf___message___Message): @@ -91,36 +82,20 @@ class ScoredVector(google___protobuf___message___Message): @property def sparse_values(self) -> type___SparseValues: ... + @property def metadata(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - id: typing___Optional[typing___Text] = None, - score: typing___Optional[builtin___float] = None, - values: typing___Optional[typing___Iterable[builtin___float]] = None, - sparse_values: typing___Optional[type___SparseValues] = None, - metadata: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - ) -> None: ... - def HasField( - self, field_name: typing_extensions___Literal["metadata", b"metadata", "sparse_values", b"sparse_values"] - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "id", - b"id", - "metadata", - b"metadata", - "score", - b"score", - "sparse_values", - b"sparse_values", - "values", - b"values", - ], - ) -> None: ... + def __init__(self, + *, + id : typing___Optional[typing___Text] = None, + score : typing___Optional[builtin___float] = None, + values : typing___Optional[typing___Iterable[builtin___float]] = None, + sparse_values : typing___Optional[type___SparseValues] = None, + metadata : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"metadata",b"metadata",u"sparse_values",b"sparse_values"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"id",b"id",u"metadata",b"metadata",u"score",b"score",u"sparse_values",b"sparse_values",u"values",b"values"]) -> None: ... type___ScoredVector = ScoredVector class UpsertRequest(google___protobuf___message___Message): @@ -129,29 +104,24 @@ class UpsertRequest(google___protobuf___message___Message): @property def vectors(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___Vector]: ... - def __init__( - self, - *, - vectors: typing___Optional[typing___Iterable[type___Vector]] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def ClearField( - self, field_name: typing_extensions___Literal["namespace", b"namespace", "vectors", b"vectors"] - ) -> None: ... + def __init__(self, + *, + vectors : typing___Optional[typing___Iterable[type___Vector]] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"namespace",b"namespace",u"vectors",b"vectors"]) -> None: ... type___UpsertRequest = UpsertRequest class UpsertResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... upserted_count: builtin___int = ... - def __init__( - self, + def __init__(self, *, - upserted_count: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["upserted_count", b"upserted_count"]) -> None: ... - + upserted_count : typing___Optional[builtin___int] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"upserted_count",b"upserted_count"]) -> None: ... type___UpsertResponse = UpsertResponse class DeleteRequest(google___protobuf___message___Message): @@ -162,31 +132,23 @@ class DeleteRequest(google___protobuf___message___Message): @property def filter(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - delete_all: typing___Optional[builtin___bool] = None, - namespace: typing___Optional[typing___Text] = None, - filter: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["filter", b"filter"]) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "delete_all", b"delete_all", "filter", b"filter", "ids", b"ids", "namespace", b"namespace" - ], - ) -> None: ... + def __init__(self, + *, + ids : typing___Optional[typing___Iterable[typing___Text]] = None, + delete_all : typing___Optional[builtin___bool] = None, + namespace : typing___Optional[typing___Text] = None, + filter : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"filter",b"filter"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"delete_all",b"delete_all",u"filter",b"filter",u"ids",b"ids",u"namespace",b"namespace"]) -> None: ... type___DeleteRequest = DeleteRequest class DeleteResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - def __init__( - self, - ) -> None: ... - + def __init__(self, + ) -> None: ... type___DeleteResponse = DeleteResponse class FetchRequest(google___protobuf___message___Message): @@ -194,49 +156,43 @@ class FetchRequest(google___protobuf___message___Message): ids: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... namespace: typing___Text = ... - def __init__( - self, + def __init__(self, *, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["ids", b"ids", "namespace", b"namespace"]) -> None: ... - + ids : typing___Optional[typing___Iterable[typing___Text]] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"ids",b"ids",u"namespace",b"namespace"]) -> None: ... type___FetchRequest = FetchRequest class FetchResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - class VectorsEntry(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... key: typing___Text = ... @property def value(self) -> type___Vector: ... - def __init__( - self, + + def __init__(self, *, - key: typing___Optional[typing___Text] = None, - value: typing___Optional[type___Vector] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["value", b"value"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal["key", b"key", "value", b"value"]) -> None: ... + key : typing___Optional[typing___Text] = None, + value : typing___Optional[type___Vector] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"value",b"value"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"key",b"key",u"value",b"value"]) -> None: ... type___VectorsEntry = VectorsEntry namespace: typing___Text = ... @property def vectors(self) -> typing___MutableMapping[typing___Text, type___Vector]: ... - def __init__( - self, - *, - vectors: typing___Optional[typing___Mapping[typing___Text, type___Vector]] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def ClearField( - self, field_name: typing_extensions___Literal["namespace", b"namespace", "vectors", b"vectors"] - ) -> None: ... + def __init__(self, + *, + vectors : typing___Optional[typing___Mapping[typing___Text, type___Vector]] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"namespace",b"namespace",u"vectors",b"vectors"]) -> None: ... type___FetchResponse = FetchResponse class QueryVector(google___protobuf___message___Message): @@ -247,36 +203,20 @@ class QueryVector(google___protobuf___message___Message): @property def sparse_values(self) -> type___SparseValues: ... + @property def filter(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - values: typing___Optional[typing___Iterable[builtin___float]] = None, - sparse_values: typing___Optional[type___SparseValues] = None, - top_k: typing___Optional[builtin___int] = None, - namespace: typing___Optional[typing___Text] = None, - filter: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - ) -> None: ... - def HasField( - self, field_name: typing_extensions___Literal["filter", b"filter", "sparse_values", b"sparse_values"] - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "filter", - b"filter", - "namespace", - b"namespace", - "sparse_values", - b"sparse_values", - "top_k", - b"top_k", - "values", - b"values", - ], - ) -> None: ... + def __init__(self, + *, + values : typing___Optional[typing___Iterable[builtin___float]] = None, + sparse_values : typing___Optional[type___SparseValues] = None, + top_k : typing___Optional[builtin___int] = None, + namespace : typing___Optional[typing___Text] = None, + filter : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"filter",b"filter",u"sparse_values",b"sparse_values"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"filter",b"filter",u"namespace",b"namespace",u"sparse_values",b"sparse_values",u"top_k",b"top_k",u"values",b"values"]) -> None: ... type___QueryVector = QueryVector class QueryRequest(google___protobuf___message___Message): @@ -290,52 +230,27 @@ class QueryRequest(google___protobuf___message___Message): @property def filter(self) -> google___protobuf___struct_pb2___Struct: ... + @property - def queries( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___QueryVector]: ... + def queries(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___QueryVector]: ... + @property def sparse_vector(self) -> type___SparseValues: ... - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - top_k: typing___Optional[builtin___int] = None, - filter: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - include_values: typing___Optional[builtin___bool] = None, - include_metadata: typing___Optional[builtin___bool] = None, - queries: typing___Optional[typing___Iterable[type___QueryVector]] = None, - vector: typing___Optional[typing___Iterable[builtin___float]] = None, - sparse_vector: typing___Optional[type___SparseValues] = None, - id: typing___Optional[typing___Text] = None, - ) -> None: ... - def HasField( - self, field_name: typing_extensions___Literal["filter", b"filter", "sparse_vector", b"sparse_vector"] - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___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: ... + def __init__(self, + *, + namespace : typing___Optional[typing___Text] = None, + top_k : typing___Optional[builtin___int] = None, + filter : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + include_values : typing___Optional[builtin___bool] = None, + include_metadata : typing___Optional[builtin___bool] = None, + queries : typing___Optional[typing___Iterable[type___QueryVector]] = None, + vector : typing___Optional[typing___Iterable[builtin___float]] = None, + sparse_vector : typing___Optional[type___SparseValues] = None, + id : typing___Optional[typing___Text] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"filter",b"filter",u"sparse_vector",b"sparse_vector"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"filter",b"filter",u"id",b"id",u"include_metadata",b"include_metadata",u"include_values",b"include_values",u"namespace",b"namespace",u"queries",b"queries",u"sparse_vector",b"sparse_vector",u"top_k",b"top_k",u"vector",b"vector"]) -> None: ... type___QueryRequest = QueryRequest class SingleQueryResults(google___protobuf___message___Message): @@ -343,19 +258,14 @@ class SingleQueryResults(google___protobuf___message___Message): namespace: typing___Text = ... @property - def matches( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredVector]: ... - def __init__( - self, - *, - matches: typing___Optional[typing___Iterable[type___ScoredVector]] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def ClearField( - self, field_name: typing_extensions___Literal["matches", b"matches", "namespace", b"namespace"] - ) -> None: ... + def matches(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredVector]: ... + def __init__(self, + *, + matches : typing___Optional[typing___Iterable[type___ScoredVector]] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"matches",b"matches",u"namespace",b"namespace"]) -> None: ... type___SingleQueryResults = SingleQueryResults class QueryResponse(google___protobuf___message___Message): @@ -363,27 +273,18 @@ class QueryResponse(google___protobuf___message___Message): namespace: typing___Text = ... @property - def results( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___SingleQueryResults]: ... + def results(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___SingleQueryResults]: ... + @property - def matches( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredVector]: ... - def __init__( - self, - *, - results: typing___Optional[typing___Iterable[type___SingleQueryResults]] = None, - matches: typing___Optional[typing___Iterable[type___ScoredVector]] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "matches", b"matches", "namespace", b"namespace", "results", b"results" - ], - ) -> None: ... + def matches(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredVector]: ... + def __init__(self, + *, + results : typing___Optional[typing___Iterable[type___SingleQueryResults]] = None, + matches : typing___Optional[typing___Iterable[type___ScoredVector]] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"matches",b"matches",u"namespace",b"namespace",u"results",b"results"]) -> None: ... type___QueryResponse = QueryResponse class UpdateRequest(google___protobuf___message___Message): @@ -394,46 +295,27 @@ class UpdateRequest(google___protobuf___message___Message): @property def sparse_values(self) -> type___SparseValues: ... + @property def set_metadata(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - id: typing___Optional[typing___Text] = None, - values: typing___Optional[typing___Iterable[builtin___float]] = None, - sparse_values: typing___Optional[type___SparseValues] = None, - set_metadata: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - namespace: typing___Optional[typing___Text] = None, - ) -> None: ... - def HasField( - self, - field_name: typing_extensions___Literal["set_metadata", b"set_metadata", "sparse_values", b"sparse_values"], - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "id", - b"id", - "namespace", - b"namespace", - "set_metadata", - b"set_metadata", - "sparse_values", - b"sparse_values", - "values", - b"values", - ], - ) -> None: ... + def __init__(self, + *, + id : typing___Optional[typing___Text] = None, + values : typing___Optional[typing___Iterable[builtin___float]] = None, + sparse_values : typing___Optional[type___SparseValues] = None, + set_metadata : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + namespace : typing___Optional[typing___Text] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"set_metadata",b"set_metadata",u"sparse_values",b"sparse_values"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"id",b"id",u"namespace",b"namespace",u"set_metadata",b"set_metadata",u"sparse_values",b"sparse_values",u"values",b"values"]) -> None: ... type___UpdateRequest = UpdateRequest class UpdateResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - def __init__( - self, - ) -> None: ... - + def __init__(self, + ) -> None: ... type___UpdateResponse = UpdateResponse class DescribeIndexStatsRequest(google___protobuf___message___Message): @@ -441,46 +323,42 @@ class DescribeIndexStatsRequest(google___protobuf___message___Message): @property def filter(self) -> google___protobuf___struct_pb2___Struct: ... - def __init__( - self, - *, - filter: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["filter", b"filter"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal["filter", b"filter"]) -> None: ... + def __init__(self, + *, + filter : typing___Optional[google___protobuf___struct_pb2___Struct] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"filter",b"filter"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"filter",b"filter"]) -> None: ... type___DescribeIndexStatsRequest = DescribeIndexStatsRequest class NamespaceSummary(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... vector_count: builtin___int = ... - def __init__( - self, + def __init__(self, *, - vector_count: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["vector_count", b"vector_count"]) -> None: ... - + vector_count : typing___Optional[builtin___int] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"vector_count",b"vector_count"]) -> None: ... type___NamespaceSummary = NamespaceSummary class DescribeIndexStatsResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - class NamespacesEntry(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... key: typing___Text = ... @property def value(self) -> type___NamespaceSummary: ... - def __init__( - self, + + def __init__(self, *, - key: typing___Optional[typing___Text] = None, - value: typing___Optional[type___NamespaceSummary] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["value", b"value"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal["key", b"key", "value", b"value"]) -> None: ... + key : typing___Optional[typing___Text] = None, + value : typing___Optional[type___NamespaceSummary] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"value",b"value"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"key",b"key",u"value",b"value"]) -> None: ... type___NamespacesEntry = NamespacesEntry dimension: builtin___int = ... @@ -489,26 +367,13 @@ class DescribeIndexStatsResponse(google___protobuf___message___Message): @property def namespaces(self) -> typing___MutableMapping[typing___Text, type___NamespaceSummary]: ... - def __init__( - self, - *, - namespaces: typing___Optional[typing___Mapping[typing___Text, type___NamespaceSummary]] = None, - dimension: typing___Optional[builtin___int] = None, - index_fullness: typing___Optional[builtin___float] = None, - total_vector_count: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "dimension", - b"dimension", - "index_fullness", - b"index_fullness", - "namespaces", - b"namespaces", - "total_vector_count", - b"total_vector_count", - ], - ) -> None: ... + def __init__(self, + *, + namespaces : typing___Optional[typing___Mapping[typing___Text, type___NamespaceSummary]] = None, + dimension : typing___Optional[builtin___int] = None, + index_fullness : typing___Optional[builtin___float] = None, + total_vector_count : typing___Optional[builtin___int] = None, + ) -> None: ... + def ClearField(self, field_name: typing_extensions___Literal[u"dimension",b"dimension",u"index_fullness",b"index_fullness",u"namespaces",b"namespaces",u"total_vector_count",b"total_vector_count"]) -> None: ... type___DescribeIndexStatsResponse = DescribeIndexStatsResponse diff --git a/pinecone/core/grpc/protos/vector_service_pb2_grpc.py b/pinecone/core/grpc/protos/vector_service_pb2_grpc.py index 2d7a899db..9688e5aed 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2_grpc.py +++ b/pinecone/core/grpc/protos/vector_service_pb2_grpc.py @@ -4,7 +4,6 @@ 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. @@ -17,35 +16,35 @@ def __init__(self, channel): 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, - ) + '/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, - ) + '/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, - ) + '/VectorService/Fetch', + request_serializer=vector__service__pb2.FetchRequest.SerializeToString, + response_deserializer=vector__service__pb2.FetchResponse.FromString, + ) self.Query = channel.unary_unary( - "/VectorService/Query", - request_serializer=vector__service__pb2.QueryRequest.SerializeToString, - response_deserializer=vector__service__pb2.QueryResponse.FromString, - ) + '/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, - ) + '/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, - ) + '/VectorService/DescribeIndexStats', + request_serializer=vector__service__pb2.DescribeIndexStatsRequest.SerializeToString, + response_deserializer=vector__service__pb2.DescribeIndexStatsResponse.FromString, + ) class VectorServiceServicer(object): @@ -60,8 +59,8 @@ def Upsert(self, request, context): If a new value is upserted for an existing vector id, it will overwrite the previous value. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') def Delete(self, request, context): """Delete @@ -70,8 +69,8 @@ def Delete(self, request, context): You can delete items by their id, from a single namespace. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') def Fetch(self, request, context): """Fetch @@ -80,8 +79,8 @@ def Fetch(self, request, context): The returned vectors include the vector data and/or metadata. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') def Query(self, request, context): """Query @@ -90,8 +89,8 @@ def Query(self, request, context): It retrieves the ids of the most similar items in a namespace, along with their similarity scores. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') def Update(self, request, context): """Update @@ -101,8 +100,8 @@ def Update(self, request, context): If a set_metadata is included, the values of the fields specified in it will be added or overwrite the previous value. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') def DescribeIndexStats(self, request, context): """DescribeIndexStats @@ -115,223 +114,152 @@ def DescribeIndexStats(self, request, context): [`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!") + 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, - ), - "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, - ), + '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, + ), + '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) + 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. + # 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, + def Upsert(request, target, - "/VectorService/Upsert", + 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, - ) + 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, + def Delete(request, target, - "/VectorService/Delete", + 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, - ) + 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, + def Fetch(request, target, - "/VectorService/Fetch", + 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, - ) + 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, + def Query(request, target, - "/VectorService/Query", + 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, - ) + 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, + def Update(request, target, - "/VectorService/Update", + 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, - ) + 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, + def DescribeIndexStats(request, target, - "/VectorService/DescribeIndexStats", + 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, - ) + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index c2250352c..e295af7fe 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -10,7 +10,7 @@ from pinecone.config import Config -from pinecone.core.client.models.sparse_values import SparseValues +from pinecone.core.client.models import SparseValues from pinecone.core.client import ApiClient from pinecone.core.client.models import ( FetchResponse, @@ -69,10 +69,10 @@ def parse_query_response(response: QueryResponse, unary_query: bool): if unary_query: - response.results = None + response._data_store.pop("results", None) else: - response.matches = None - response.namespace = None + response._data_store.pop("matches", None) + response._data_store.pop("namespace", None) return response diff --git a/poetry.lock b/poetry.lock index 1060d39a9..ff1d212fd 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,17 +1,5 @@ # This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. -[[package]] -name = "aenum" -version = "3.1.11" -description = "Advanced Enumerations (compatible with Python's stdlib Enum), NamedTuples, and NamedConstants" -optional = false -python-versions = "*" -files = [ - {file = "aenum-3.1.11-py2-none-any.whl", hash = "sha256:525b4870a27d0b471c265bda692bc657f1e0dd7597ad4186d072c59f9db666f6"}, - {file = "aenum-3.1.11-py3-none-any.whl", hash = "sha256:12ae89967f2e25c0ce28c293955d643f891603488bc3d9946158ba2b35203638"}, - {file = "aenum-3.1.11.tar.gz", hash = "sha256:aed2c273547ae72a0d5ee869719c02a643da16bf507c80958faadc7e038e3f73"}, -] - [[package]] name = "astunparse" version = "1.6.3" @@ -707,58 +695,6 @@ files = [ {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, ] -[[package]] -name = "pydantic" -version = "1.10.12" -description = "Data validation and settings management using python type hints" -optional = false -python-versions = ">=3.7" -files = [ - {file = "pydantic-1.10.12-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a1fcb59f2f355ec350073af41d927bf83a63b50e640f4dbaa01053a28b7a7718"}, - {file = "pydantic-1.10.12-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b7ccf02d7eb340b216ec33e53a3a629856afe1c6e0ef91d84a4e6f2fb2ca70fe"}, - {file = "pydantic-1.10.12-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8fb2aa3ab3728d950bcc885a2e9eff6c8fc40bc0b7bb434e555c215491bcf48b"}, - {file = "pydantic-1.10.12-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:771735dc43cf8383959dc9b90aa281f0b6092321ca98677c5fb6125a6f56d58d"}, - {file = "pydantic-1.10.12-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:ca48477862372ac3770969b9d75f1bf66131d386dba79506c46d75e6b48c1e09"}, - {file = "pydantic-1.10.12-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:a5e7add47a5b5a40c49b3036d464e3c7802f8ae0d1e66035ea16aa5b7a3923ed"}, - {file = "pydantic-1.10.12-cp310-cp310-win_amd64.whl", hash = "sha256:e4129b528c6baa99a429f97ce733fff478ec955513630e61b49804b6cf9b224a"}, - {file = "pydantic-1.10.12-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b0d191db0f92dfcb1dec210ca244fdae5cbe918c6050b342d619c09d31eea0cc"}, - {file = "pydantic-1.10.12-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:795e34e6cc065f8f498c89b894a3c6da294a936ee71e644e4bd44de048af1405"}, - {file = "pydantic-1.10.12-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:69328e15cfda2c392da4e713443c7dbffa1505bc9d566e71e55abe14c97ddc62"}, - {file = "pydantic-1.10.12-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2031de0967c279df0d8a1c72b4ffc411ecd06bac607a212892757db7462fc494"}, - {file = "pydantic-1.10.12-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:ba5b2e6fe6ca2b7e013398bc7d7b170e21cce322d266ffcd57cca313e54fb246"}, - {file = "pydantic-1.10.12-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:2a7bac939fa326db1ab741c9d7f44c565a1d1e80908b3797f7f81a4f86bc8d33"}, - {file = "pydantic-1.10.12-cp311-cp311-win_amd64.whl", hash = "sha256:87afda5539d5140cb8ba9e8b8c8865cb5b1463924d38490d73d3ccfd80896b3f"}, - {file = "pydantic-1.10.12-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:549a8e3d81df0a85226963611950b12d2d334f214436a19537b2efed61b7639a"}, - {file = "pydantic-1.10.12-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598da88dfa127b666852bef6d0d796573a8cf5009ffd62104094a4fe39599565"}, - {file = "pydantic-1.10.12-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba5c4a8552bff16c61882db58544116d021d0b31ee7c66958d14cf386a5b5350"}, - {file = "pydantic-1.10.12-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:c79e6a11a07da7374f46970410b41d5e266f7f38f6a17a9c4823db80dadf4303"}, - {file = "pydantic-1.10.12-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:ab26038b8375581dc832a63c948f261ae0aa21f1d34c1293469f135fa92972a5"}, - {file = "pydantic-1.10.12-cp37-cp37m-win_amd64.whl", hash = "sha256:e0a16d274b588767602b7646fa05af2782576a6cf1022f4ba74cbb4db66f6ca8"}, - {file = "pydantic-1.10.12-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6a9dfa722316f4acf4460afdf5d41d5246a80e249c7ff475c43a3a1e9d75cf62"}, - {file = "pydantic-1.10.12-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:a73f489aebd0c2121ed974054cb2759af8a9f747de120acd2c3394cf84176ccb"}, - {file = "pydantic-1.10.12-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b30bcb8cbfccfcf02acb8f1a261143fab622831d9c0989707e0e659f77a18e0"}, - {file = "pydantic-1.10.12-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2fcfb5296d7877af406ba1547dfde9943b1256d8928732267e2653c26938cd9c"}, - {file = "pydantic-1.10.12-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:2f9a6fab5f82ada41d56b0602606a5506aab165ca54e52bc4545028382ef1c5d"}, - {file = "pydantic-1.10.12-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:dea7adcc33d5d105896401a1f37d56b47d443a2b2605ff8a969a0ed5543f7e33"}, - {file = "pydantic-1.10.12-cp38-cp38-win_amd64.whl", hash = "sha256:1eb2085c13bce1612da8537b2d90f549c8cbb05c67e8f22854e201bde5d98a47"}, - {file = "pydantic-1.10.12-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ef6c96b2baa2100ec91a4b428f80d8f28a3c9e53568219b6c298c1125572ebc6"}, - {file = "pydantic-1.10.12-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6c076be61cd0177a8433c0adcb03475baf4ee91edf5a4e550161ad57fc90f523"}, - {file = "pydantic-1.10.12-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2d5a58feb9a39f481eda4d5ca220aa8b9d4f21a41274760b9bc66bfd72595b86"}, - {file = "pydantic-1.10.12-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e5f805d2d5d0a41633651a73fa4ecdd0b3d7a49de4ec3fadf062fe16501ddbf1"}, - {file = "pydantic-1.10.12-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:1289c180abd4bd4555bb927c42ee42abc3aee02b0fb2d1223fb7c6e5bef87dbe"}, - {file = "pydantic-1.10.12-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5d1197e462e0364906cbc19681605cb7c036f2475c899b6f296104ad42b9f5fb"}, - {file = "pydantic-1.10.12-cp39-cp39-win_amd64.whl", hash = "sha256:fdbdd1d630195689f325c9ef1a12900524dceb503b00a987663ff4f58669b93d"}, - {file = "pydantic-1.10.12-py3-none-any.whl", hash = "sha256:b749a43aa51e32839c9d71dc67eb1e4221bb04af1033a32e3923d46f9effa942"}, - {file = "pydantic-1.10.12.tar.gz", hash = "sha256:0fe8a415cea8f340e7a9af9c54fc71a649b43e8ca3cc732986116b3cb135d303"}, -] - -[package.dependencies] -typing-extensions = ">=4.2.0" - -[package.extras] -dotenv = ["python-dotenv (>=0.10.4)"] -email = ["email-validator (>=1.0.3)"] - [[package]] name = "pygments" version = "2.16.1" @@ -1114,4 +1050,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "59c7274e14abcf26e77715ecca2f5339ef46f61d1a267e3701e0031e607f5792" +content-hash = "a533d1e09ab2ff0c50d91cf5d2ec52c1c112e6e11a79738f47c2a1847035782f" diff --git a/pyproject.toml b/pyproject.toml index 61c905ef9..4c545766f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,8 +69,6 @@ grpc-gateway-protoc-gen-openapiv2 = "0.1.0" googleapis-common-protos = ">=1.53.0" lz4 = ">=3.1.3" protobuf = "~=3.20.0" -aenum = "3.1.11" -pydantic = "1.10.12" [tool.poetry.group.dev.dependencies] pdoc = "^14.1.0" diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index b15c5acd1..1d54e736b 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -1,6 +1,5 @@ import pytest from pinecone import Pinecone -from pinecone.core.client.api import IndexOperationsApi import time class TestControl: @@ -24,43 +23,24 @@ def test_passing_host(self): (-1, [{"status": {"ready": False}}], 0, 0), ]) def test_create_index_with_timeout(self, mocker, timeout_value, describe_index_responses, expected_describe_index_calls, expected_sleep_calls): - mocker.patch.object(IndexOperationsApi, 'describe_index', side_effect=describe_index_responses) - mocker.patch.object(IndexOperationsApi, 'create_index') + p = Pinecone(api_key="123-456-789") + mocker.patch.object(p.index_api, 'describe_index', side_effect=describe_index_responses) + mocker.patch.object(p.index_api, 'create_index') mocker.patch('time.sleep') - p = Pinecone(api_key="123-456-789") p.create_index("my-index", 10, timeout=timeout_value, cloud="aws", region="us-west1", capacity_mode="pod") - assert IndexOperationsApi.create_index.call_count == 1 - assert IndexOperationsApi.describe_index.call_count == expected_describe_index_calls + assert p.index_api.create_index.call_count == 1 + assert p.index_api.describe_index.call_count == expected_describe_index_calls assert time.sleep.call_count == expected_sleep_calls def test_create_index_when_timeout_exceeded(self, mocker): with pytest.raises(TimeoutError): - get_status_responses = [{"status": {"ready": False}}] * 5 - mocker.patch.object(IndexOperationsApi, 'describe_index', side_effect=get_status_responses) - mocker.patch.object(IndexOperationsApi, 'create_index') - mocker.patch('time.sleep') - p = Pinecone(api_key="123-456-789") - p.create_index("my-index", 10, timeout=10, cloud="aws", region="us-west1", capacity_mode="pod") - - # @pytest.mark.parametrize("timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses", [ - # # No timeout, list_indexes called twice, sleep called once - # (None, 2, 1, [["my-index", "index-1"], ["index-1"]]), - # # Timeout of 10 seconds, list_indexes called 3 times, sleep twice - # (10, 3, 2, [["my-index", "index-1"], ["my-index", "index-1"], ["index-1"]]), - # # Timeout of -1 seconds, list_indexes not called, no sleep - # (-1, 0, 0, [["my-index", "index-1"]]), - # ]) - # def test_delete_index_with_timeout(self, mocker, timeout_value, list_indexes_calls, time_sleep_calls, list_indexes_responses): - # api_instance_mock = mocker.Mock() - # api_instance_mock.list_indexes = mocker.Mock(side_effect=list_indexes_responses) - # mocker.patch('pinecone.manage._get_api_instance', return_value=api_instance_mock) - # mocker.patch('time.sleep') + mocker.patch.object(p.index_api, 'create_index') - # pinecone.manage.delete_index("my-index", timeout=timeout_value) + describe_index_response = [{"status": {"ready": False}}] * 5 + mocker.patch.object(p.index_api, 'describe_index', side_effect=describe_index_response) + mocker.patch('time.sleep') - # pinecone.manage._get_api_instance.assert_called_once() - # assert api_instance_mock.list_indexes.call_count == list_indexes_calls - # assert time.sleep.call_count == time_sleep_calls \ No newline at end of file + p.create_index("my-index", 10, timeout=10, cloud="aws", region="us-west1", capacity_mode="pod") diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index de90bad23..d37bb1d9c 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -3,7 +3,6 @@ import pytest import pinecone -from pinecone.config import PineconeConfig from pinecone import Index from pinecone import UpsertRequest, Vector from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse, UpsertResponse, SparseValues @@ -356,7 +355,6 @@ def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): response = QueryResponse( results=[], matches=[ScoredVector(id="1", score=0.9, values=[0.0], metadata={"a": 2})], namespace="test" ) - mocker.patch.object(self.index._vector_api, "query", autospec=True, return_value=response) actual = self.index.query(top_k=10, vector=self.vals1) From d7219a10274366f32a8b22cb99b0c81ceecb7612 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 3 Nov 2023 14:32:57 -0400 Subject: [PATCH 04/39] [spruce] Pin docs-build python version (#235) ## Problem This is a cherry-pick of changes in #234 onto the spruce branch. I want this change in both `main` and `spruce` but rebasing spruce or merging main into spruce is complicated due to the number of open PR branches on spruce at the moment. ## Solution Describe the approach you took. Link to any relevant bugs, issues, docs, or other resources. ## Type of Change - [x] Infrastructure change (CI configs, etc) --- .github/actions/build-docs/action.yml | 7 ++++++- .github/workflows/merge.yaml | 2 ++ .github/workflows/pr.yaml | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/actions/build-docs/action.yml b/.github/actions/build-docs/action.yml index 63181c448..32166afcb 100644 --- a/.github/actions/build-docs/action.yml +++ b/.github/actions/build-docs/action.yml @@ -1,12 +1,17 @@ name: 'Build client documentation' description: 'Generates client documentation using pdoc' +inputs: + python-version: + description: 'Python version to use' + required: true + default: '3.x' runs: using: 'composite' steps: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: 3.x + python-version: ${{ inputs.python-version }} - name: Setup Poetry uses: ./.github/actions/setup-poetry diff --git a/.github/workflows/merge.yaml b/.github/workflows/merge.yaml index 5528aaa41..0b7585130 100644 --- a/.github/workflows/merge.yaml +++ b/.github/workflows/merge.yaml @@ -15,6 +15,8 @@ jobs: - name: Generate pdoc documentation uses: ./.github/actions/build-docs + with: + python-version: 3.11 - name: Deploy documentation to gh-pages uses: s0/git-publish-subdir-action@develop diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index d92cbc1ee..d61f74946 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -19,3 +19,5 @@ jobs: uses: actions/checkout@v3 - name: Build docs with pdoc uses: './.github/actions/build-docs' + with: + python-version: 3.11 \ No newline at end of file From 85fce4f1ab7a5393cb378b9a94ba3136e808d36d Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 3 Nov 2023 20:30:48 -0400 Subject: [PATCH 05/39] Remove numpy dependency (#233) ## Problem Our numpy dependency causes installation problems for some users and we don't really need it. ## Solution - Dependency changes - Move `numpy` from `dependencies` into `dev.dependencies` in `pyproject.toml`. - We still need it as a dev dependency so we can use it in tests to make sure things don't blow up when users pass in numpy arrays to the `upsert` method. - Coercing inputs to `list` from pandas, numpy arrays - Implement a util function, `convert_to_list` that will cast iterables from numpy, pandas, etc to a list without any specific dependency on these packages. - Parsing user inputs to upsert - Extract a big chunk of code from `Index#upsert` and move it into a new `VectorFactory` class where it could be tested in isolation. This seemed warranted because there were many different error cases being covered in this code that parses user inputs into a `Vector` ahead of the upsert API call. (This became part of this PR because buried in the guts of it it were some numpy usages.) - Add lots of missing tests for `VectorFactory` code. - Take out the trash - Delete some legacy utils and references messing with numpy and `vector_column_service.proto` because these seemed completely disconnected from the rest of the Index/GRPCIndex code. - Remove numpy deprecation notices ## Type of Change - [x] Breaking change: Removing old utils functions that seem useless anyway - [x] None of the above: Refactor --- .../grpc/protos/vector_column_service_pb2.py | 1293 ----------------- .../grpc/protos/vector_column_service_pb2.pyi | 350 ----- .../protos/vector_column_service_pb2_grpc.py | 267 ---- pinecone/data/index.py | 96 +- pinecone/data/vector_factory.py | 111 ++ pinecone/deprecated/legacy_utils.py | 67 - pinecone/utils/__init__.py | 3 +- pinecone/utils/convert_to_list.py | 9 + poetry.lock | 2 +- pyproject.toml | 2 +- tests/unit/data/test_vector_factory.py | 139 ++ tests/unit/test_index.py | 9 - tests/unit/utils/test_convert_to_list.py | 38 + 13 files changed, 307 insertions(+), 2079 deletions(-) delete mode 100644 pinecone/data/grpc/protos/vector_column_service_pb2.py delete mode 100644 pinecone/data/grpc/protos/vector_column_service_pb2.pyi delete mode 100644 pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py create mode 100644 pinecone/data/vector_factory.py create mode 100644 pinecone/utils/convert_to_list.py create mode 100644 tests/unit/data/test_vector_factory.py create mode 100644 tests/unit/utils/test_convert_to_list.py diff --git a/pinecone/data/grpc/protos/vector_column_service_pb2.py b/pinecone/data/grpc/protos/vector_column_service_pb2.py deleted file mode 100644 index 1b4ebadc1..000000000 --- a/pinecone/data/grpc/protos/vector_column_service_pb2.py +++ /dev/null @@ -1,1293 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: vector_column_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="vector_column_service.proto", - package="pinecone_columnar", - syntax="proto3", - serialized_options=b"\n\021io.pinecone.protoZ+github.com/pinecone-io/go-pinecone/pinecone", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n\x1bvector_column_service.proto\x12\x11pinecone_columnar\x1a\x1cgoogle/protobuf/struct.proto"K\n\x07NdArray\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\x0c\x12\r\n\x05shape\x18\x02 \x03(\r\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\x12\n\ncompressed\x18\x04 \x01(\x08"\xbc\x01\n\rScoredResults\x12\'\n\x03ids\x18\x01 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray\x12*\n\x06scores\x18\x02 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray\x12(\n\x04\x64\x61ta\x18\x03 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray\x12,\n\x08metadata\x18\x04 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray"\x84\x01\n\rUpsertRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0b\n\x03ids\x18\x02 \x03(\t\x12(\n\x04\x64\x61ta\x18\x03 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray\x12)\n\x08metadata\x18\x04 \x03(\x0b\x32\x17.google.protobuf.Struct"(\n\x0eUpsertResponse\x12\x16\n\x0eupserted_count\x18\x01 \x01(\r"C\n\rDeleteRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0b\n\x03ids\x18\x02 \x03(\t\x12\x12\n\ndelete_all\x18\x03 \x01(\x08"\x10\n\x0e\x44\x65leteResponse".\n\x0c\x46\x65tchRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0b\n\x03ids\x18\x02 \x03(\t"\x87\x01\n\rFetchResponse\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x0b\n\x03ids\x18\x02 \x03(\t\x12+\n\x07vectors\x18\x03 \x03(\x0b\x32\x1a.pinecone_columnar.NdArray\x12)\n\x08metadata\x18\x04 \x03(\x0b\x32\x17.google.protobuf.Struct"\xa1\x02\n\x0cQueryRequest\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x1b\n\x13namespace_overrides\x18\x06 \x03(\t\x12\r\n\x05top_k\x18\x02 \x01(\r\x12\x17\n\x0ftop_k_overrides\x18\x05 \x03(\r\x12\'\n\x06\x66ilter\x18\x07 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x31\n\x10\x66ilter_overrides\x18\x08 \x03(\x0b\x32\x17.google.protobuf.Struct\x12\x16\n\x0einclude_values\x18\x03 \x01(\x08\x12\x18\n\x10include_metadata\x18\t \x01(\x08\x12+\n\x07queries\x18\x04 \x01(\x0b\x32\x1a.pinecone_columnar.NdArray"B\n\rQueryResponse\x12\x31\n\x07matches\x18\x01 \x03(\x0b\x32 .pinecone_columnar.ScoredResults"\x1b\n\x19\x44\x65scribeIndexStatsRequest"(\n\x10NamespaceSummary\x12\x14\n\x0cvector_count\x18\x01 \x01(\r"\xda\x01\n\x1a\x44\x65scribeIndexStatsResponse\x12Q\n\nnamespaces\x18\x01 \x03(\x0b\x32=.pinecone_columnar.DescribeIndexStatsResponse.NamespacesEntry\x12\x11\n\tdimension\x18\x02 \x01(\r\x1aV\n\x0fNamespacesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.pinecone_columnar.NamespaceSummary:\x02\x38\x01\x32\xc8\x03\n\x13VectorColumnService\x12O\n\x06Upsert\x12 .pinecone_columnar.UpsertRequest\x1a!.pinecone_columnar.UpsertResponse"\x00\x12O\n\x06\x44\x65lete\x12 .pinecone_columnar.DeleteRequest\x1a!.pinecone_columnar.DeleteResponse"\x00\x12L\n\x05\x46\x65tch\x12\x1f.pinecone_columnar.FetchRequest\x1a .pinecone_columnar.FetchResponse"\x00\x12L\n\x05Query\x12\x1f.pinecone_columnar.QueryRequest\x1a .pinecone_columnar.QueryResponse"\x00\x12s\n\x12\x44\x65scribeIndexStats\x12,.pinecone_columnar.DescribeIndexStatsRequest\x1a-.pinecone_columnar.DescribeIndexStatsResponse"\x00\x42@\n\x11io.pinecone.protoZ+github.com/pinecone-io/go-pinecone/pineconeb\x06proto3', - dependencies=[ - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - ], -) - - -_NDARRAY = _descriptor.Descriptor( - name="NdArray", - full_name="pinecone_columnar.NdArray", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="buffer", - full_name="pinecone_columnar.NdArray.buffer", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="shape", - full_name="pinecone_columnar.NdArray.shape", - index=1, - number=2, - type=13, - cpp_type=3, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dtype", - full_name="pinecone_columnar.NdArray.dtype", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compressed", - full_name="pinecone_columnar.NdArray.compressed", - index=3, - number=4, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=80, - serialized_end=155, -) - - -_SCOREDRESULTS = _descriptor.Descriptor( - name="ScoredResults", - full_name="pinecone_columnar.ScoredResults", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="ids", - full_name="pinecone_columnar.ScoredResults.ids", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="scores", - full_name="pinecone_columnar.ScoredResults.scores", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="pinecone_columnar.ScoredResults.data", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="pinecone_columnar.ScoredResults.metadata", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=158, - serialized_end=346, -) - - -_UPSERTREQUEST = _descriptor.Descriptor( - name="UpsertRequest", - full_name="pinecone_columnar.UpsertRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="pinecone_columnar.UpsertRequest.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ids", - full_name="pinecone_columnar.UpsertRequest.ids", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="pinecone_columnar.UpsertRequest.data", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="pinecone_columnar.UpsertRequest.metadata", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=349, - serialized_end=481, -) - - -_UPSERTRESPONSE = _descriptor.Descriptor( - name="UpsertResponse", - full_name="pinecone_columnar.UpsertResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="upserted_count", - full_name="pinecone_columnar.UpsertResponse.upserted_count", - index=0, - number=1, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=483, - serialized_end=523, -) - - -_DELETEREQUEST = _descriptor.Descriptor( - name="DeleteRequest", - full_name="pinecone_columnar.DeleteRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="pinecone_columnar.DeleteRequest.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ids", - full_name="pinecone_columnar.DeleteRequest.ids", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="delete_all", - full_name="pinecone_columnar.DeleteRequest.delete_all", - index=2, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=525, - serialized_end=592, -) - - -_DELETERESPONSE = _descriptor.Descriptor( - name="DeleteResponse", - full_name="pinecone_columnar.DeleteResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=594, - serialized_end=610, -) - - -_FETCHREQUEST = _descriptor.Descriptor( - name="FetchRequest", - full_name="pinecone_columnar.FetchRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="pinecone_columnar.FetchRequest.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ids", - full_name="pinecone_columnar.FetchRequest.ids", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=612, - serialized_end=658, -) - - -_FETCHRESPONSE = _descriptor.Descriptor( - name="FetchResponse", - full_name="pinecone_columnar.FetchResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="pinecone_columnar.FetchResponse.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ids", - full_name="pinecone_columnar.FetchResponse.ids", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="vectors", - full_name="pinecone_columnar.FetchResponse.vectors", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="metadata", - full_name="pinecone_columnar.FetchResponse.metadata", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=661, - serialized_end=796, -) - - -_QUERYREQUEST = _descriptor.Descriptor( - name="QueryRequest", - full_name="pinecone_columnar.QueryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespace", - full_name="pinecone_columnar.QueryRequest.namespace", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="namespace_overrides", - full_name="pinecone_columnar.QueryRequest.namespace_overrides", - index=1, - number=6, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="top_k", - full_name="pinecone_columnar.QueryRequest.top_k", - index=2, - number=2, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="top_k_overrides", - full_name="pinecone_columnar.QueryRequest.top_k_overrides", - index=3, - number=5, - type=13, - cpp_type=3, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="pinecone_columnar.QueryRequest.filter", - index=4, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter_overrides", - full_name="pinecone_columnar.QueryRequest.filter_overrides", - index=5, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="include_values", - full_name="pinecone_columnar.QueryRequest.include_values", - index=6, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="include_metadata", - full_name="pinecone_columnar.QueryRequest.include_metadata", - index=7, - number=9, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="queries", - full_name="pinecone_columnar.QueryRequest.queries", - index=8, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=799, - serialized_end=1088, -) - - -_QUERYRESPONSE = _descriptor.Descriptor( - name="QueryResponse", - full_name="pinecone_columnar.QueryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matches", - full_name="pinecone_columnar.QueryResponse.matches", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1090, - serialized_end=1156, -) - - -_DESCRIBEINDEXSTATSREQUEST = _descriptor.Descriptor( - name="DescribeIndexStatsRequest", - full_name="pinecone_columnar.DescribeIndexStatsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1158, - serialized_end=1185, -) - - -_NAMESPACESUMMARY = _descriptor.Descriptor( - name="NamespaceSummary", - full_name="pinecone_columnar.NamespaceSummary", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vector_count", - full_name="pinecone_columnar.NamespaceSummary.vector_count", - index=0, - number=1, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1187, - serialized_end=1227, -) - - -_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY = _descriptor.Descriptor( - name="NamespacesEntry", - full_name="pinecone_columnar.DescribeIndexStatsResponse.NamespacesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="pinecone_columnar.DescribeIndexStatsResponse.NamespacesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="pinecone_columnar.DescribeIndexStatsResponse.NamespacesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1362, - serialized_end=1448, -) - -_DESCRIBEINDEXSTATSRESPONSE = _descriptor.Descriptor( - name="DescribeIndexStatsResponse", - full_name="pinecone_columnar.DescribeIndexStatsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="namespaces", - full_name="pinecone_columnar.DescribeIndexStatsResponse.namespaces", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dimension", - full_name="pinecone_columnar.DescribeIndexStatsResponse.dimension", - index=1, - number=2, - type=13, - cpp_type=3, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1230, - serialized_end=1448, -) - -_SCOREDRESULTS.fields_by_name["ids"].message_type = _NDARRAY -_SCOREDRESULTS.fields_by_name["scores"].message_type = _NDARRAY -_SCOREDRESULTS.fields_by_name["data"].message_type = _NDARRAY -_SCOREDRESULTS.fields_by_name["metadata"].message_type = _NDARRAY -_UPSERTREQUEST.fields_by_name["data"].message_type = _NDARRAY -_UPSERTREQUEST.fields_by_name["metadata"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_FETCHRESPONSE.fields_by_name["vectors"].message_type = _NDARRAY -_FETCHRESPONSE.fields_by_name["metadata"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_QUERYREQUEST.fields_by_name["filter"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_QUERYREQUEST.fields_by_name["filter_overrides"].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_QUERYREQUEST.fields_by_name["queries"].message_type = _NDARRAY -_QUERYRESPONSE.fields_by_name["matches"].message_type = _SCOREDRESULTS -_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY.fields_by_name["value"].message_type = _NAMESPACESUMMARY -_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY.containing_type = _DESCRIBEINDEXSTATSRESPONSE -_DESCRIBEINDEXSTATSRESPONSE.fields_by_name["namespaces"].message_type = _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY -DESCRIPTOR.message_types_by_name["NdArray"] = _NDARRAY -DESCRIPTOR.message_types_by_name["ScoredResults"] = _SCOREDRESULTS -DESCRIPTOR.message_types_by_name["UpsertRequest"] = _UPSERTREQUEST -DESCRIPTOR.message_types_by_name["UpsertResponse"] = _UPSERTRESPONSE -DESCRIPTOR.message_types_by_name["DeleteRequest"] = _DELETEREQUEST -DESCRIPTOR.message_types_by_name["DeleteResponse"] = _DELETERESPONSE -DESCRIPTOR.message_types_by_name["FetchRequest"] = _FETCHREQUEST -DESCRIPTOR.message_types_by_name["FetchResponse"] = _FETCHRESPONSE -DESCRIPTOR.message_types_by_name["QueryRequest"] = _QUERYREQUEST -DESCRIPTOR.message_types_by_name["QueryResponse"] = _QUERYRESPONSE -DESCRIPTOR.message_types_by_name["DescribeIndexStatsRequest"] = _DESCRIBEINDEXSTATSREQUEST -DESCRIPTOR.message_types_by_name["NamespaceSummary"] = _NAMESPACESUMMARY -DESCRIPTOR.message_types_by_name["DescribeIndexStatsResponse"] = _DESCRIBEINDEXSTATSRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -NdArray = _reflection.GeneratedProtocolMessageType( - "NdArray", - (_message.Message,), - { - "DESCRIPTOR": _NDARRAY, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.NdArray) - }, -) -_sym_db.RegisterMessage(NdArray) - -ScoredResults = _reflection.GeneratedProtocolMessageType( - "ScoredResults", - (_message.Message,), - { - "DESCRIPTOR": _SCOREDRESULTS, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.ScoredResults) - }, -) -_sym_db.RegisterMessage(ScoredResults) - -UpsertRequest = _reflection.GeneratedProtocolMessageType( - "UpsertRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPSERTREQUEST, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.UpsertRequest) - }, -) -_sym_db.RegisterMessage(UpsertRequest) - -UpsertResponse = _reflection.GeneratedProtocolMessageType( - "UpsertResponse", - (_message.Message,), - { - "DESCRIPTOR": _UPSERTRESPONSE, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.UpsertResponse) - }, -) -_sym_db.RegisterMessage(UpsertResponse) - -DeleteRequest = _reflection.GeneratedProtocolMessageType( - "DeleteRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEREQUEST, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.DeleteRequest) - }, -) -_sym_db.RegisterMessage(DeleteRequest) - -DeleteResponse = _reflection.GeneratedProtocolMessageType( - "DeleteResponse", - (_message.Message,), - { - "DESCRIPTOR": _DELETERESPONSE, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.DeleteResponse) - }, -) -_sym_db.RegisterMessage(DeleteResponse) - -FetchRequest = _reflection.GeneratedProtocolMessageType( - "FetchRequest", - (_message.Message,), - { - "DESCRIPTOR": _FETCHREQUEST, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.FetchRequest) - }, -) -_sym_db.RegisterMessage(FetchRequest) - -FetchResponse = _reflection.GeneratedProtocolMessageType( - "FetchResponse", - (_message.Message,), - { - "DESCRIPTOR": _FETCHRESPONSE, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.FetchResponse) - }, -) -_sym_db.RegisterMessage(FetchResponse) - -QueryRequest = _reflection.GeneratedProtocolMessageType( - "QueryRequest", - (_message.Message,), - { - "DESCRIPTOR": _QUERYREQUEST, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.QueryRequest) - }, -) -_sym_db.RegisterMessage(QueryRequest) - -QueryResponse = _reflection.GeneratedProtocolMessageType( - "QueryResponse", - (_message.Message,), - { - "DESCRIPTOR": _QUERYRESPONSE, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.QueryResponse) - }, -) -_sym_db.RegisterMessage(QueryResponse) - -DescribeIndexStatsRequest = _reflection.GeneratedProtocolMessageType( - "DescribeIndexStatsRequest", - (_message.Message,), - { - "DESCRIPTOR": _DESCRIBEINDEXSTATSREQUEST, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.DescribeIndexStatsRequest) - }, -) -_sym_db.RegisterMessage(DescribeIndexStatsRequest) - -NamespaceSummary = _reflection.GeneratedProtocolMessageType( - "NamespaceSummary", - (_message.Message,), - { - "DESCRIPTOR": _NAMESPACESUMMARY, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.NamespaceSummary) - }, -) -_sym_db.RegisterMessage(NamespaceSummary) - -DescribeIndexStatsResponse = _reflection.GeneratedProtocolMessageType( - "DescribeIndexStatsResponse", - (_message.Message,), - { - "NamespacesEntry": _reflection.GeneratedProtocolMessageType( - "NamespacesEntry", - (_message.Message,), - { - "DESCRIPTOR": _DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.DescribeIndexStatsResponse.NamespacesEntry) - }, - ), - "DESCRIPTOR": _DESCRIBEINDEXSTATSRESPONSE, - "__module__": "vector_column_service_pb2" - # @@protoc_insertion_point(class_scope:pinecone_columnar.DescribeIndexStatsResponse) - }, -) -_sym_db.RegisterMessage(DescribeIndexStatsResponse) -_sym_db.RegisterMessage(DescribeIndexStatsResponse.NamespacesEntry) - - -DESCRIPTOR._options = None -_DESCRIBEINDEXSTATSRESPONSE_NAMESPACESENTRY._options = None - -_VECTORCOLUMNSERVICE = _descriptor.ServiceDescriptor( - name="VectorColumnService", - full_name="pinecone_columnar.VectorColumnService", - file=DESCRIPTOR, - index=0, - serialized_options=None, - create_key=_descriptor._internal_create_key, - serialized_start=1451, - serialized_end=1907, - methods=[ - _descriptor.MethodDescriptor( - name="Upsert", - full_name="pinecone_columnar.VectorColumnService.Upsert", - index=0, - containing_service=None, - input_type=_UPSERTREQUEST, - output_type=_UPSERTRESPONSE, - serialized_options=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Delete", - full_name="pinecone_columnar.VectorColumnService.Delete", - index=1, - containing_service=None, - input_type=_DELETEREQUEST, - output_type=_DELETERESPONSE, - serialized_options=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Fetch", - full_name="pinecone_columnar.VectorColumnService.Fetch", - index=2, - containing_service=None, - input_type=_FETCHREQUEST, - output_type=_FETCHRESPONSE, - serialized_options=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="Query", - full_name="pinecone_columnar.VectorColumnService.Query", - index=3, - containing_service=None, - input_type=_QUERYREQUEST, - output_type=_QUERYRESPONSE, - serialized_options=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DescribeIndexStats", - full_name="pinecone_columnar.VectorColumnService.DescribeIndexStats", - index=4, - containing_service=None, - input_type=_DESCRIBEINDEXSTATSREQUEST, - output_type=_DESCRIBEINDEXSTATSRESPONSE, - serialized_options=None, - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_VECTORCOLUMNSERVICE) - -DESCRIPTOR.services_by_name["VectorColumnService"] = _VECTORCOLUMNSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/pinecone/data/grpc/protos/vector_column_service_pb2.pyi b/pinecone/data/grpc/protos/vector_column_service_pb2.pyi deleted file mode 100644 index 3b85ddb13..000000000 --- a/pinecone/data/grpc/protos/vector_column_service_pb2.pyi +++ /dev/null @@ -1,350 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, - FileDescriptor as google___protobuf___descriptor___FileDescriptor, -) - -from google.protobuf.internal.containers import ( - RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, - RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from google.protobuf.struct_pb2 import ( - Struct as google___protobuf___struct_pb2___Struct, -) - -from typing import ( - Iterable as typing___Iterable, - Mapping as typing___Mapping, - MutableMapping as typing___MutableMapping, - Optional as typing___Optional, - Text as typing___Text, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - -DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ... - -class NdArray(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - buffer: builtin___bytes = ... - shape: google___protobuf___internal___containers___RepeatedScalarFieldContainer[builtin___int] = ... - dtype: typing___Text = ... - compressed: builtin___bool = ... - - def __init__( - self, - *, - buffer: typing___Optional[builtin___bytes] = None, - shape: typing___Optional[typing___Iterable[builtin___int]] = None, - dtype: typing___Optional[typing___Text] = None, - compressed: typing___Optional[builtin___bool] = None, - ) -> None: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "buffer", b"buffer", "compressed", b"compressed", "dtype", b"dtype", "shape", b"shape" - ], - ) -> None: ... - -type___NdArray = NdArray - -class ScoredResults(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - @property - def ids(self) -> type___NdArray: ... - @property - def scores(self) -> type___NdArray: ... - @property - def data(self) -> type___NdArray: ... - @property - def metadata(self) -> type___NdArray: ... - def __init__( - self, - *, - ids: typing___Optional[type___NdArray] = None, - scores: typing___Optional[type___NdArray] = None, - data: typing___Optional[type___NdArray] = None, - metadata: typing___Optional[type___NdArray] = None, - ) -> None: ... - def HasField( - self, - field_name: typing_extensions___Literal[ - "data", b"data", "ids", b"ids", "metadata", b"metadata", "scores", b"scores" - ], - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "data", b"data", "ids", b"ids", "metadata", b"metadata", "scores", b"scores" - ], - ) -> None: ... - -type___ScoredResults = ScoredResults - -class UpsertRequest(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - namespace: typing___Text = ... - ids: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... - - @property - def data(self) -> type___NdArray: ... - @property - def metadata( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[ - google___protobuf___struct_pb2___Struct - ]: ... - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - data: typing___Optional[type___NdArray] = None, - metadata: typing___Optional[typing___Iterable[google___protobuf___struct_pb2___Struct]] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["data", b"data"]) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "data", b"data", "ids", b"ids", "metadata", b"metadata", "namespace", b"namespace" - ], - ) -> None: ... - -type___UpsertRequest = UpsertRequest - -class UpsertResponse(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - upserted_count: builtin___int = ... - - def __init__( - self, - *, - upserted_count: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["upserted_count", b"upserted_count"]) -> None: ... - -type___UpsertResponse = UpsertResponse - -class DeleteRequest(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - namespace: typing___Text = ... - ids: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... - delete_all: builtin___bool = ... - - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - delete_all: typing___Optional[builtin___bool] = None, - ) -> None: ... - def ClearField( - self, - field_name: typing_extensions___Literal["delete_all", b"delete_all", "ids", b"ids", "namespace", b"namespace"], - ) -> None: ... - -type___DeleteRequest = DeleteRequest - -class DeleteResponse(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - def __init__( - self, - ) -> None: ... - -type___DeleteResponse = DeleteResponse - -class FetchRequest(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - namespace: typing___Text = ... - ids: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... - - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["ids", b"ids", "namespace", b"namespace"]) -> None: ... - -type___FetchRequest = FetchRequest - -class FetchResponse(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - namespace: typing___Text = ... - ids: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... - - @property - def vectors( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___NdArray]: ... - @property - def metadata( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[ - google___protobuf___struct_pb2___Struct - ]: ... - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - ids: typing___Optional[typing___Iterable[typing___Text]] = None, - vectors: typing___Optional[typing___Iterable[type___NdArray]] = None, - metadata: typing___Optional[typing___Iterable[google___protobuf___struct_pb2___Struct]] = None, - ) -> None: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "ids", b"ids", "metadata", b"metadata", "namespace", b"namespace", "vectors", b"vectors" - ], - ) -> None: ... - -type___FetchResponse = FetchResponse - -class QueryRequest(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - namespace: typing___Text = ... - namespace_overrides: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ... - top_k: builtin___int = ... - top_k_overrides: google___protobuf___internal___containers___RepeatedScalarFieldContainer[builtin___int] = ... - include_values: builtin___bool = ... - include_metadata: builtin___bool = ... - - @property - def filter(self) -> google___protobuf___struct_pb2___Struct: ... - @property - def filter_overrides( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[ - google___protobuf___struct_pb2___Struct - ]: ... - @property - def queries(self) -> type___NdArray: ... - def __init__( - self, - *, - namespace: typing___Optional[typing___Text] = None, - namespace_overrides: typing___Optional[typing___Iterable[typing___Text]] = None, - top_k: typing___Optional[builtin___int] = None, - top_k_overrides: typing___Optional[typing___Iterable[builtin___int]] = None, - filter: typing___Optional[google___protobuf___struct_pb2___Struct] = None, - filter_overrides: typing___Optional[typing___Iterable[google___protobuf___struct_pb2___Struct]] = None, - include_values: typing___Optional[builtin___bool] = None, - include_metadata: typing___Optional[builtin___bool] = None, - queries: typing___Optional[type___NdArray] = None, - ) -> None: ... - def HasField( - self, field_name: typing_extensions___Literal["filter", b"filter", "queries", b"queries"] - ) -> builtin___bool: ... - def ClearField( - self, - field_name: typing_extensions___Literal[ - "filter", - b"filter", - "filter_overrides", - b"filter_overrides", - "include_metadata", - b"include_metadata", - "include_values", - b"include_values", - "namespace", - b"namespace", - "namespace_overrides", - b"namespace_overrides", - "queries", - b"queries", - "top_k", - b"top_k", - "top_k_overrides", - b"top_k_overrides", - ], - ) -> None: ... - -type___QueryRequest = QueryRequest - -class QueryResponse(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - @property - def matches( - self, - ) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredResults]: ... - def __init__( - self, - *, - matches: typing___Optional[typing___Iterable[type___ScoredResults]] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["matches", b"matches"]) -> None: ... - -type___QueryResponse = QueryResponse - -class DescribeIndexStatsRequest(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - def __init__( - self, - ) -> None: ... - -type___DescribeIndexStatsRequest = DescribeIndexStatsRequest - -class NamespaceSummary(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - vector_count: builtin___int = ... - - def __init__( - self, - *, - vector_count: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal["vector_count", b"vector_count"]) -> None: ... - -type___NamespaceSummary = NamespaceSummary - -class DescribeIndexStatsResponse(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - class NamespacesEntry(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - key: typing___Text = ... - - @property - def value(self) -> type___NamespaceSummary: ... - def __init__( - self, - *, - key: typing___Optional[typing___Text] = None, - value: typing___Optional[type___NamespaceSummary] = None, - ) -> None: ... - def HasField(self, field_name: typing_extensions___Literal["value", b"value"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal["key", b"key", "value", b"value"]) -> None: ... - type___NamespacesEntry = NamespacesEntry - - dimension: builtin___int = ... - - @property - def namespaces(self) -> typing___MutableMapping[typing___Text, type___NamespaceSummary]: ... - def __init__( - self, - *, - namespaces: typing___Optional[typing___Mapping[typing___Text, type___NamespaceSummary]] = None, - dimension: typing___Optional[builtin___int] = None, - ) -> None: ... - def ClearField( - self, field_name: typing_extensions___Literal["dimension", b"dimension", "namespaces", b"namespaces"] - ) -> None: ... - -type___DescribeIndexStatsResponse = DescribeIndexStatsResponse diff --git a/pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py b/pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py deleted file mode 100644 index 677e12b4b..000000000 --- a/pinecone/data/grpc/protos/vector_column_service_pb2_grpc.py +++ /dev/null @@ -1,267 +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_column_service_pb2 as vector__column__service__pb2 - - -class VectorColumnServiceStub(object): - """The `VectorColumnService` interface is exposed by Pinecone vector index services. - The `Upsert` operation is for uploading the data (the vector ids and values) to be indexed. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.Upsert = channel.unary_unary( - "/pinecone_columnar.VectorColumnService/Upsert", - request_serializer=vector__column__service__pb2.UpsertRequest.SerializeToString, - response_deserializer=vector__column__service__pb2.UpsertResponse.FromString, - ) - self.Delete = channel.unary_unary( - "/pinecone_columnar.VectorColumnService/Delete", - request_serializer=vector__column__service__pb2.DeleteRequest.SerializeToString, - response_deserializer=vector__column__service__pb2.DeleteResponse.FromString, - ) - self.Fetch = channel.unary_unary( - "/pinecone_columnar.VectorColumnService/Fetch", - request_serializer=vector__column__service__pb2.FetchRequest.SerializeToString, - response_deserializer=vector__column__service__pb2.FetchResponse.FromString, - ) - self.Query = channel.unary_unary( - "/pinecone_columnar.VectorColumnService/Query", - request_serializer=vector__column__service__pb2.QueryRequest.SerializeToString, - response_deserializer=vector__column__service__pb2.QueryResponse.FromString, - ) - self.DescribeIndexStats = channel.unary_unary( - "/pinecone_columnar.VectorColumnService/DescribeIndexStats", - request_serializer=vector__column__service__pb2.DescribeIndexStatsRequest.SerializeToString, - response_deserializer=vector__column__service__pb2.DescribeIndexStatsResponse.FromString, - ) - - -class VectorColumnServiceServicer(object): - """The `VectorColumnService` interface is exposed by Pinecone vector index services. - The `Upsert` operation is for uploading the data (the vector ids and values) to be indexed. - """ - - def Upsert(self, request, context): - """If a user upserts a new value for an existing vector id, it overwrites the previous value.""" - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Delete(self, request, context): - """The `Delete` operation deletes multiple vectors ids from a single namespace. - Specifying `delete_all` will delete all vectors from the default namespace. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Fetch(self, request, context): - """The `Fetch` operation returns a vector value by id.""" - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def Query(self, request, context): - """The `Query` operation queries the index for the nearest stored vectors to one - or more query vectors, and returns their ids and/or values. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DescribeIndexStats(self, request, context): - """The `DescribeIndexStats` operation returns summary statistics about the index contents.""" - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_VectorColumnServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "Upsert": grpc.unary_unary_rpc_method_handler( - servicer.Upsert, - request_deserializer=vector__column__service__pb2.UpsertRequest.FromString, - response_serializer=vector__column__service__pb2.UpsertResponse.SerializeToString, - ), - "Delete": grpc.unary_unary_rpc_method_handler( - servicer.Delete, - request_deserializer=vector__column__service__pb2.DeleteRequest.FromString, - response_serializer=vector__column__service__pb2.DeleteResponse.SerializeToString, - ), - "Fetch": grpc.unary_unary_rpc_method_handler( - servicer.Fetch, - request_deserializer=vector__column__service__pb2.FetchRequest.FromString, - response_serializer=vector__column__service__pb2.FetchResponse.SerializeToString, - ), - "Query": grpc.unary_unary_rpc_method_handler( - servicer.Query, - request_deserializer=vector__column__service__pb2.QueryRequest.FromString, - response_serializer=vector__column__service__pb2.QueryResponse.SerializeToString, - ), - "DescribeIndexStats": grpc.unary_unary_rpc_method_handler( - servicer.DescribeIndexStats, - request_deserializer=vector__column__service__pb2.DescribeIndexStatsRequest.FromString, - response_serializer=vector__column__service__pb2.DescribeIndexStatsResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler("pinecone_columnar.VectorColumnService", rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class VectorColumnService(object): - """The `VectorColumnService` interface is exposed by Pinecone vector index services. - The `Upsert` operation is for uploading the data (the vector ids and values) to be indexed. - """ - - @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, - "/pinecone_columnar.VectorColumnService/Upsert", - vector__column__service__pb2.UpsertRequest.SerializeToString, - vector__column__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, - "/pinecone_columnar.VectorColumnService/Delete", - vector__column__service__pb2.DeleteRequest.SerializeToString, - vector__column__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, - "/pinecone_columnar.VectorColumnService/Fetch", - vector__column__service__pb2.FetchRequest.SerializeToString, - vector__column__service__pb2.FetchResponse.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, - "/pinecone_columnar.VectorColumnService/Query", - vector__column__service__pb2.QueryRequest.SerializeToString, - vector__column__service__pb2.QueryResponse.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, - "/pinecone_columnar.VectorColumnService/DescribeIndexStats", - vector__column__service__pb2.DescribeIndexStatsRequest.SerializeToString, - vector__column__service__pb2.DescribeIndexStatsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index e295af7fe..1b8e70f01 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -1,11 +1,6 @@ -import os - from tqdm.autonotebook import tqdm -from importlib.util import find_spec -import numbers -import numpy as np -from collections.abc import Iterable, Mapping +from collections.abc import Iterable from typing import Union, List, Tuple, Optional, Dict, Any from pinecone.config import Config @@ -30,8 +25,8 @@ DescribeIndexStatsRequest, ) from pinecone.core.client.api.vector_operations_api import VectorOperationsApi -from ..utils import fix_tuple_length, get_user_agent, warn_deprecated -import copy +from ..utils import get_user_agent, fix_tuple_length +from .vector_factory import VectorFactory __all__ = [ "Index", @@ -53,7 +48,6 @@ "SparseValues", ] -from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS from ..utils.error_handling import validate_and_convert_errors _OPENAPI_ENDPOINT_PARAMS = ( @@ -66,7 +60,6 @@ "async_req", ) - def parse_query_response(response: QueryResponse, unary_query: bool): if unary_query: response._data_store.pop("results", None) @@ -75,13 +68,6 @@ def parse_query_response(response: QueryResponse, unary_query: bool): response._data_store.pop("namespace", None) return response - -def upsert_numpy_deprecation_notice(context): - numpy_deprecataion_notice = "The ability to pass a numpy ndarray as part of a dictionary argument to upsert() will be removed in a future version of the pinecone client. To remove this warning, use the numpy.ndarray.tolist method to convert your ndarray into a python list before calling upsert()." - message = " ".join([context, numpy_deprecataion_notice]) - warn_deprecated(message, deprecated_in="2.2.1", removal_in="3.0.0") - - class Index(): """ @@ -168,7 +154,7 @@ def upsert( Returns: UpsertResponse, includes the number of vectors upserted. """ - _check_type = kwargs.pop("_check_type", False) + _check_type = kwargs.pop("_check_type", True) if kwargs.get("async_req", False) and batch_size is not None: raise ValueError( @@ -197,81 +183,11 @@ def _upsert_batch( self, vectors: List[Vector], namespace: Optional[str], _check_type: bool, **kwargs ) -> UpsertResponse: args_dict = self._parse_non_empty_args([("namespace", namespace)]) - - def _dict_to_vector(item): - item_keys = set(item.keys()) - if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): - raise ValueError( - f"Vector dictionary is missing required fields: {list(REQUIRED_VECTOR_FIELDS - item_keys)}" - ) - - excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) - if len(excessive_keys) > 0: - raise ValueError( - f"Found excess keys in the vector dictionary: {list(excessive_keys)}. " - f"The allowed keys are: {list(REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS)}" - ) - - if "sparse_values" in item: - if not isinstance(item["sparse_values"], Mapping): - raise ValueError( - f"Column `sparse_values` is expected to be a dictionary, found {type(item['sparse_values'])}" - ) - - indices = item["sparse_values"].get("indices", None) - values = item["sparse_values"].get("values", None) - - if isinstance(values, np.ndarray): - upsert_numpy_deprecation_notice("Deprecated type passed in sparse_values['values'].") - values = values.tolist() - if isinstance(indices, np.ndarray): - upsert_numpy_deprecation_notice("Deprecated type passed in sparse_values['indices'].") - indices = indices.tolist() - try: - item["sparse_values"] = SparseValues(indices=indices, values=values) - except TypeError as e: - raise ValueError( - "Found unexpected data in column `sparse_values`. " - "Expected format is `'sparse_values': {'indices': List[int], 'values': List[float]}`." - ) from e - - if "metadata" in item: - metadata = item.get("metadata") - if not isinstance(metadata, Mapping): - raise TypeError(f"Column `metadata` is expected to be a dictionary, found {type(metadata)}") - - if isinstance(item["values"], np.ndarray): - upsert_numpy_deprecation_notice("Deprecated type passed in 'values'.") - item["values"] = item["values"].tolist() - - try: - return Vector(**item) - except TypeError as e: - # if not isinstance(item['values'], Iterable) or not isinstance(item['values'][0], numbers.Real): - # raise TypeError(f"Column `values` is expected to be a list of floats") - if not isinstance(item["values"], Iterable) or not isinstance(item["values"][0], numbers.Real): - raise TypeError(f"Column `values` is expected to be a list of floats") - raise - - def _vector_transform(item: Union[Vector, Tuple]): - if isinstance(item, Vector): - return item - elif isinstance(item, tuple): - if len(item) > 3: - raise ValueError( - f"Found a tuple of length {len(item)} which is not supported. " - f"Vectors can be represented as tuples either the form (id, values, metadata) or (id, values). " - f"To pass sparse values please use either dicts or a Vector objects as inputs." - ) - id, values, metadata = fix_tuple_length(item, 3) - return Vector(id=id, values=values, metadata=metadata or {}, _check_type=_check_type) - elif isinstance(item, Mapping): - return _dict_to_vector(item) - raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + vec_builder = lambda v: VectorFactory.build(v, check_type=_check_type) return self._vector_api.upsert( UpsertRequest( - vectors=list(map(_vector_transform, vectors)), + vectors=list(map(vec_builder, vectors)), **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS}, diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py new file mode 100644 index 000000000..831df4f12 --- /dev/null +++ b/pinecone/data/vector_factory.py @@ -0,0 +1,111 @@ +import numbers + +from collections.abc import Iterable, Mapping +from typing import Union, Tuple, Dict + +from ..utils import fix_tuple_length, convert_to_list +from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS + +from pinecone.core.client.models import ( + Vector, + SparseValues +) + +class VectorDictionaryMissingKeysError(ValueError): + def __init__(self, item): + message = f"Vector dictionary is missing required fields: {list(REQUIRED_VECTOR_FIELDS - set(item.keys()))}" + super().__init__(message) + +class VectorDictionaryExcessKeysError(ValueError): + def __init__(self, item): + invalid_keys = list(set(item.keys()) - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS)) + message = f"Found excess keys in the vector dictionary: {invalid_keys}. The allowed keys are: {list(REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS)}" + super().__init__(message) + +class VectorTupleLengthError(ValueError): + def __init__(self, item): + message = f"Found a tuple of length {len(item)} which is not supported. Vectors can be represented as tuples either the form (id, values, metadata) or (id, values). To pass sparse values please use either dicts or a Vector objects as inputs." + super().__init__(message) + +class SparseValuesTypeError(ValueError): + def __init__(self): + message = "Found unexpected data in column `sparse_values`. Expected format is `'sparse_values': {'indices': List[int], 'values': List[float]}`." + super().__init__(message) + +class SparseValuesMissingKeysError(ValueError): + def __init__(self, sparse_values_dict): + message = f"Missing required keys in data in column `sparse_values`. Expected format is `'sparse_values': {{'indices': List[int], 'values': List[float]}}`. Found keys {list(sparse_values_dict.keys())}" + super().__init__(message) + +class SparseValuesDictionaryExpectedError(ValueError): + def __init__(self, sparse_values_dict): + message = f"Column `sparse_values` is expected to be a dictionary, found {type(sparse_values_dict)}" + super().__init__(message) + +class MetadataDictionaryExpectedError(ValueError): + def __init__(self, item): + message = f"Column `metadata` is expected to be a dictionary, found {type(item['metadata'])}" + super().__init__(message) + +class VectorFactory: + @staticmethod + def build(item: Union[Vector, Tuple, Dict], check_type: bool = True) -> Vector: + if isinstance(item, Vector): + return item + elif isinstance(item, tuple): + return VectorFactory._tuple_to_vector(item, check_type) + elif isinstance(item, Mapping): + return VectorFactory._dict_to_vector(item, check_type) + else: + raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + + @staticmethod + def _tuple_to_vector(item, check_type: bool) -> Vector: + if len(item) < 2 or len(item) > 3: + raise VectorTupleLengthError(item) + id, values, metadata = fix_tuple_length(item, 3) + return Vector(id=id, values=convert_to_list(values), metadata=metadata or {}, _check_type=check_type) + + @staticmethod + def _dict_to_vector(item, check_type: bool) -> Vector: + item_keys = set(item.keys()) + if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): + raise VectorDictionaryMissingKeysError(item) + + excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) + if len(excessive_keys) > 0: + raise VectorDictionaryExcessKeysError(item) + + values = item.get("values") + if "values" in item: + item["values"] = convert_to_list(values) + + sparse_values = item.get("sparse_values") + if sparse_values and not isinstance(sparse_values, SparseValues): + item["sparse_values"] = VectorFactory._dict_to_sparse_values(sparse_values, check_type) + + metadata = item.get("metadata") + if metadata and not isinstance(metadata, Mapping): + raise MetadataDictionaryExpectedError(item) + + try: + return Vector(**item, _check_type=check_type) + except TypeError as e: + if not isinstance(item["values"], Iterable) or not isinstance(item["values"][0], numbers.Real): + raise TypeError(f"Column `values` is expected to be a list of floats") + raise e + + @staticmethod + def _dict_to_sparse_values(sparse_values_dict: Dict, check_type: bool) -> SparseValues: + if not isinstance(sparse_values_dict, Mapping): + raise SparseValuesDictionaryExpectedError(sparse_values_dict) + if not {"indices", "values"}.issubset(sparse_values_dict): + raise SparseValuesMissingKeysError(sparse_values_dict) + + indices = convert_to_list(sparse_values_dict.get("indices")) + values = convert_to_list(sparse_values_dict.get("values")) + + try: + return SparseValues(indices=indices, values=values, _check_type=check_type) + except TypeError: + raise SparseValuesTypeError() \ No newline at end of file diff --git a/pinecone/deprecated/legacy_utils.py b/pinecone/deprecated/legacy_utils.py index 19b5f58ec..f614f80d6 100644 --- a/pinecone/deprecated/legacy_utils.py +++ b/pinecone/deprecated/legacy_utils.py @@ -1,51 +1,13 @@ import re -import uuid -from typing import List - -from pinecone.utils import warn_deprecated try: - from pinecone.data.grpc.protos import vector_column_service_pb2 from google.protobuf.struct_pb2 import Struct from google.protobuf import json_format - import numpy as np - import lz4.frame except Exception: pass # ignore for non-[grpc] installations DNS_COMPATIBLE_REGEX = re.compile("^[a-z0-9]([a-z0-9]|[-])+[a-z0-9]$") - -def dump_numpy_public(np_array: "np.ndarray", compressed: bool = False) -> "vector_column_service_pb2.NdArray": - """ - Dump numpy array to vector_column_service_pb2.NdArray - """ - warn_deprecated( - "dump_numpy_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - protobuf_arr = vector_column_service_pb2.NdArray() - protobuf_arr.dtype = str(np_array.dtype) - protobuf_arr.shape.extend(np_array.shape) - if compressed: - protobuf_arr.buffer = lz4.frame.compress(np_array.tobytes()) - protobuf_arr.compressed = True - else: - protobuf_arr.buffer = np_array.tobytes() - return protobuf_arr - - -def dump_strings_public(strs: List[str], compressed: bool = False) -> "vector_column_service_pb2.NdArray": - warn_deprecated( - "dump_strings_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - return dump_numpy_public(np.array(strs, dtype="S"), compressed=compressed) - - - def validate_dns_name(name): if not DNS_COMPATIBLE_REGEX.match(name): raise ValueError( @@ -57,32 +19,3 @@ def validate_dns_name(name): def proto_struct_to_dict(s: "Struct") -> dict: return json_format.MessageToDict(s) - - -def load_numpy_public(proto_arr: "vector_column_service_pb2.NdArray") -> "np.ndarray": - """ - Load numpy array from protobuf - :param proto_arr: - :return: - """ - warn_deprecated( - "load_numpy_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - if len(proto_arr.shape) == 0: - return np.array([]) - if proto_arr.compressed: - numpy_arr = np.frombuffer(lz4.frame.decompress(proto_arr.buffer), dtype=proto_arr.dtype) - else: - numpy_arr = np.frombuffer(proto_arr.buffer, dtype=proto_arr.dtype) - return numpy_arr.reshape(proto_arr.shape) - - -def load_strings_public(proto_arr: "vector_column_service_pb2.NdArray") -> List[str]: - warn_deprecated( - "load_strings_public and all numpy-related features will be removed in a future version", - deprecated_in="2.2.1", - removal_in="3.0.0", - ) - return [str(item, "utf-8") for item in load_numpy_public(proto_arr)] diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py index c826e0ff7..8c2c486a2 100644 --- a/pinecone/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -2,4 +2,5 @@ from .environment import get_version, get_environment from .user_agent import get_user_agent from .deprecation_notice import warn_deprecated -from .fix_tuple_length import fix_tuple_length \ No newline at end of file +from .fix_tuple_length import fix_tuple_length +from .convert_to_list import convert_to_list \ No newline at end of file diff --git a/pinecone/utils/convert_to_list.py b/pinecone/utils/convert_to_list.py new file mode 100644 index 000000000..ecaf45902 --- /dev/null +++ b/pinecone/utils/convert_to_list.py @@ -0,0 +1,9 @@ +def convert_to_list(obj): + class_name = obj.__class__.__name__ + + if class_name == 'list': + return obj + elif hasattr(obj, 'tolist'): + return obj.tolist() + else: + return list(obj) \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index ff1d212fd..90b7fb33a 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1050,4 +1050,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "a533d1e09ab2ff0c50d91cf5d2ec52c1c112e6e11a79738f47c2a1847035782f" +content-hash = "eb925f93e12e47feb53591724acc3a48b1f33d913798f610ce6506bda52aa38c" diff --git a/pyproject.toml b/pyproject.toml index 4c545766f..24bf7617a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,6 @@ dnspython = ">=2.0.0" python-dateutil = ">=2.5.3" urllib3 = "1.25.3" tqdm = ">=4.64.1" -numpy = ">=1.22.0" grpcio = ">=1.44.0" grpc-gateway-protoc-gen-openapiv2 = "0.1.0" googleapis-common-protos = ">=1.53.0" @@ -71,6 +70,7 @@ lz4 = ">=3.1.3" protobuf = "~=3.20.0" [tool.poetry.group.dev.dependencies] +numpy = ">=1.22" pdoc = "^14.1.0" pytest = "6.2.4" pytest-asyncio = "0.15.1" diff --git a/tests/unit/data/test_vector_factory.py b/tests/unit/data/test_vector_factory.py new file mode 100644 index 000000000..bf713a660 --- /dev/null +++ b/tests/unit/data/test_vector_factory.py @@ -0,0 +1,139 @@ +import numpy as np +import pandas as pd +import pytest + +from pinecone.data.vector_factory import VectorFactory +from pinecone import Vector, SparseValues + +class TestVectorFactory: + 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 + + def test_build_when_tuple_with_two_values(self): + tup = ('1', [0.1, 0.2, 0.3]) + actual = VectorFactory.build(tup) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={}) + assert actual == expected + + def test_build_when_tuple_with_three_values(self): + tup = ('1', [0.1, 0.2, 0.3], {'genre': 'comedy'}) + actual = VectorFactory.build(tup) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}) + assert actual == expected + + def test_build_when_tuple_with_numpy_array(self): + tup = ('1', np.array([0.1, 0.2, 0.3]), {'genre': 'comedy'}) + actual = VectorFactory.build(tup) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}) + assert actual == expected + + def test_build_when_tuple_with_pandas_array(self): + tup = ('1', pd.array([0.1, 0.2, 0.3])) + actual = VectorFactory.build(tup) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={}) + 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"): + tup = ('1', [0.1, 0.2, 0.3], {'a': 'b'}, 'extra') + VectorFactory.build(tup) + + def test_build_when_tuple_too_short(self): + with pytest.raises(ValueError, match="Found a tuple of length 1 which is not supported"): + tup = ('1',) + VectorFactory.build(tup) + + def test_build_when_dict(self): + d = { 'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}) + assert actual == expected + + def test_build_when_dict_with_numpy_values(self): + d = { 'id': '1', 'values': np.array([0.1, 0.2, 0.3]), 'metadata': {'genre': 'comedy'}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}) + assert actual == expected + + def test_build_when_dict_with_pandas_values(self): + d = { 'id': '1', 'values': pd.array([0.1, 0.2, 0.3]), 'metadata': {'genre': 'comedy'}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'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]} + VectorFactory.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'} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': [0, 2], 'values': [0.1, 0.3]}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_dict_sparse_values_when_SparseValues(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': SparseValues(indices=[0, 2], values=[0.1, 0.3])} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_dict_sparse_values_errors_when_not_dict(self): + with pytest.raises(ValueError, match="Column `sparse_values` is expected to be a dictionary"): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': 'not a dict'} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values_errors_when_missing_indices(self): + with pytest.raises(ValueError, match="Missing required keys in data in column `sparse_values`"): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'values': [0.1, 0.3]}} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values_errors_when_missing_values(self): + with pytest.raises(ValueError, match="Missing required keys in data in column `sparse_values`"): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': [0, 2]}} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values_errors_when_indices_not_list(self): + with pytest.raises(ValueError, match="Found unexpected data in column `sparse_values`"): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': 'not a list', 'values': [0.1, 0.3]}} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values_errors_when_values_not_list(self): + with pytest.raises(ValueError, match="Found unexpected data in column `sparse_values`"): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': [0, 2], 'values': 'not a list'}} + VectorFactory.build(d) + + def test_build_when_dict_sparse_values_when_values_is_ndarray(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': [0, 2], 'values': np.array([0.1, 0.3])}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_dict_sparse_values_when_indices_is_pandas_IntegerArray(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': pd.array([0, 2]), 'values': [0.1, 0.3]}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_dict_sparse_values_when_values_is_pandas_FloatingArray(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': [0, 2], 'values': pd.array([0.1, 0.3])}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_dict_sparse_values_when_indices_is_ndarray(self): + d = {'id': '1', 'values': [0.1, 0.2, 0.3], 'metadata': {'genre': 'comedy'}, 'sparse_values': {'indices': np.array([0, 2]), 'values': [0.1, 0.3]}} + actual = VectorFactory.build(d) + expected = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'genre': 'comedy'}, sparse_values=SparseValues(indices=[0, 2], values=[0.1, 0.3])) + assert actual == expected + + def test_build_when_errors_when_other_type(self): + with pytest.raises(ValueError, match="Invalid vector value passed: cannot interpret type"): + VectorFactory.build(1) diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index d37bb1d9c..468222b44 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -32,15 +32,6 @@ def setup_method(self): # region: upsert tests - def test_upsert_numpy_deprecation_warning(self, mocker): - mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) - with pytest.warns(FutureWarning): - # numpy used in dictionary values - self.index.upsert([{'id': '2', 'values': np.array([3.0, 3.2, 4.2])}]) - with pytest.warns(FutureWarning): - # numpy used in dictionary sparse_values - self.index.upsert([{'id': '3', 'values': [0.5,0.5,0.5], 'sparse_values': { 'indices': np.array([0, 1]), 'values': np.array([3.0, 3.2])}}]) - def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): mocker.patch.object(self.index._vector_api, "upsert", autospec=True) self.index.upsert([("vec1", self.vals1), ("vec2", self.vals2)], namespace="ns") diff --git a/tests/unit/utils/test_convert_to_list.py b/tests/unit/utils/test_convert_to_list.py new file mode 100644 index 000000000..88efc0e3b --- /dev/null +++ b/tests/unit/utils/test_convert_to_list.py @@ -0,0 +1,38 @@ +import pytest +from pinecone.utils import convert_to_list +import numpy as np +import pandas as pd + +def test_convert_to_list_when_numpy_array(): + obj = np.array([1, 2, 3]) + actual = convert_to_list(obj) + expected = [1, 2, 3] + assert actual == expected + assert actual[0].__class__ == expected[0].__class__ + +def test_convert_to_list_when_pandas_array(): + obj = pd.array([1, 2, 3]) + actual = convert_to_list(obj) + expected = [1, 2, 3] + assert actual == expected + assert actual[0].__class__ == expected[0].__class__ + +def test_convert_to_list_when_pandas_float_array(): + obj = pd.array([0.1, 0.2, 0.3]) + actual = convert_to_list(obj) + expected = [0.1, 0.2, 0.3] + assert actual == expected + assert actual[0].__class__ == expected[0].__class__ + +def test_convert_to_list_when_pandas_series(): + obj = pd.Series([1, 2, 3]) + actual = convert_to_list(obj) + expected = [1, 2, 3] + assert actual == expected + assert actual[0].__class__ == expected[0].__class__ + +def test_convert_to_list_when_already_list(): + obj = [1, 2, 3] + actual = convert_to_list(obj) + expected = [1, 2, 3] + assert actual == expected From e73726d7cf2938c5a3a9648b4fc3bdf73f64db1c Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 6 Nov 2023 09:47:17 -0800 Subject: [PATCH 06/39] Move all grpc stuff into pinecone.grpc subpackage (#238) ## Problem In the past this package attempted to import extra grpc deps in the root `__init__.py` inside a try/catch that caught `ImportError` when deps were missing. This is error prone because people may be attempting to use the `pinecone` module alongside other packages that depend on incompatible versions of these dependencies, so we shouldn't interpret successful import as a sign that a user has installed the `pinecone-client[grpc]` extras (with the versions we expect). When these incompatible versions are present, the `ImportError` doesn't happen but other runtime errors can occur even when the person is not attempting to use `GRPCIndex`. ## Solution The gist of this PR is to better isolate everything GRPC-related into a subpackage to minimize the changes of a grpc-related dependency clash getting in the way of using Pinecone. By doing this, issues with grpc dependencies should never impact people using the non-grpc client. Summary of changes: - Moving files - Contents of `pinecone/data/grpc` moved up and over to `pinecone/grpc` - Tests moved from `tests/unit/test_index_grpc.py` into `tests/unit_grpc/test_index_grpc.py`. This is to make it easier to split grpc and non-grpc test runs. - Delete remaining cruft in `pinecone/deprecated/legacy_utils.py` because they were unused and loading grpc deps. - Making `from pinecone import Pinecone` independent of GRPC - References to all GRPC deps removed from `pinecone/__init__.py` - Adjusting `pinecone/pinecone.py` to remove `IndexGRPC()` method. - Setting up for `from pinecone.grpc import Pinecone` - Add `pinecone/grpc/pinecone.yaml` that extends the other Pinecone class, modifying only the `Index()` method to use `GRPCIndex`. - Add `pinecone/grpc/__init__.py` with entries for grpc-flavored `Pinecone` and `IndexGRPC` exports. - CI updates - `pyproject.toml` adjusted to properly indicate grpc deps as `optional = true`; I discovered in testing that grpc dependencies were always being installed in CI. - Add an input var to the `setup-poetry` action so that we can toggle on grpc dependencies when needed. - `.github/workflows/testing.yaml` refactored to break GRPC and non-GRPC into separate jobs, since they have different install requirements. #### Usage evolution ##### Legacy implementation ```python import pinecone pinecone.init(api_key='foo', environment='bar') index = pinecone.Index('index-name') index_grpc = pinecone.GRPCIndex('index-name') ``` ##### Unreleased spruce branch (before this PR) This was an improvement over the legacy approach because we no longer relied on global state for configuration. Instead, we wrap configuration state into a class instance. However, the `Pinecone` class had a dependency on GRPC stuff to implement the `GRPCIndex()` method. The imports of these extra deps was intended to noop when they were not installed, but as I described above there are situations where you could still have runtime errors if other dependencies in your notebook / app have installed incompatible GRPC dependencies that prevent you from using the REST version of the client. ```python from pinecone import Pinecone p = Pinecone(api_key='foo') index = p.Index('index-name') index_grpc = p.GRPCIndex('index-name') ``` ##### After this PR, import from different subpackage when GRPC desired Now the usage is exactly the same for REST vs GRPC except for the import coming from `pinecone.grpc` instead of `pinecone` when you want data operations to use grpc. GRPC deps are not loaded at all unless you specifically import from `pinecone.grpc`. To use REST, import from `pinecone` ```python from pinecone import Pinecone p = Pinecone(api_key='foo') index = p.Index('index-name') ``` To use GRPC, import from `pinecone.grpc` subpackage ```python from pinecone.grpc import Pinecone p = Pinecone(api_key='foo') index = p.Index('index-name') ``` If you ever wanted to use these side by side for some reason (no real reason to ever do this unless you are writing tests for this package) you would have to alias one of the imports to avoid a name collision. ```python from pinecone import Pinecone from pinecone.grpc import Pinecone as PineconeGRPC ... ``` ## Type of Change - [x] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] This change requires a documentation update - [x] Infrastructure change (CI configs, etc) ## Test Plan Describe specific steps for validating this change. --- .github/actions/build-docs/action.yml | 2 + .github/actions/setup-poetry/action.yml | 7 +++ .github/workflows/testing.yaml | 54 +++++++++++++++++--- Makefile | 8 +-- pinecone/__init__.py | 7 +-- pinecone/control/pinecone.py | 5 -- pinecone/data/__init__.py | 3 +- pinecone/data/grpc/__init__.py | 0 pinecone/deprecated/__init__.py | 1 - pinecone/deprecated/legacy_utils.py | 21 -------- pinecone/grpc/__init__.py | 2 + pinecone/{data => }/grpc/base.py | 2 +- pinecone/{data => }/grpc/config.py | 0 pinecone/{data => }/grpc/future.py | 0 pinecone/{data => }/grpc/index_grpc.py | 4 +- pinecone/grpc/pinecone.py | 7 +++ pinecone/{data => }/grpc/retry.py | 0 pinecone/{data => }/grpc/utils.py | 0 poetry.lock | 12 ++--- pyproject.toml | 10 ++-- tests/{unit => unit_grpc}/test_grpc_index.py | 5 +- 21 files changed, 88 insertions(+), 62 deletions(-) delete mode 100644 pinecone/data/grpc/__init__.py delete mode 100644 pinecone/deprecated/__init__.py delete mode 100644 pinecone/deprecated/legacy_utils.py create mode 100644 pinecone/grpc/__init__.py rename pinecone/{data => }/grpc/base.py (99%) rename pinecone/{data => }/grpc/config.py (100%) rename pinecone/{data => }/grpc/future.py (100%) rename pinecone/{data => }/grpc/index_grpc.py (99%) create mode 100644 pinecone/grpc/pinecone.py rename pinecone/{data => }/grpc/retry.py (100%) rename pinecone/{data => }/grpc/utils.py (100%) rename tests/{unit => unit_grpc}/test_grpc_index.py (99%) diff --git a/.github/actions/build-docs/action.yml b/.github/actions/build-docs/action.yml index 32166afcb..e9d2f4607 100644 --- a/.github/actions/build-docs/action.yml +++ b/.github/actions/build-docs/action.yml @@ -15,6 +15,8 @@ runs: - name: Setup Poetry uses: ./.github/actions/setup-poetry + with: + include_grpc: 'true' - name: Build html documentation shell: bash diff --git a/.github/actions/setup-poetry/action.yml b/.github/actions/setup-poetry/action.yml index dae526e65..1b8f6e1b9 100644 --- a/.github/actions/setup-poetry/action.yml +++ b/.github/actions/setup-poetry/action.yml @@ -1,5 +1,10 @@ name: 'Setup Poetry' description: 'Installs Poetry and dependencies' +inputs: + include_grpc: + description: 'Install gRPC dependencies' + required: true + default: 'false' runs: using: 'composite' steps: @@ -7,6 +12,7 @@ runs: uses: snok/install-poetry@v1 - name: Install dependencies + if: ${{ inputs.include_grpc == 'false' }} shell: bash run: | poetry install @@ -16,6 +22,7 @@ runs: # The dependencies that are specific to gRPC are defined in pyproject.toml # under tool.poetry.extras - name: Install gRPC dependencies + if: ${{ inputs.include_grpc == 'true' }} shell: bash run: | poetry install --extras "grpc" diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 61b7ec05d..bf3c599c4 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -4,8 +4,8 @@ on: workflow_call: {} jobs: - run-tests: - name: Run tests + units-no-grpc: + name: Run tests (REST) runs-on: ubuntu-latest strategy: matrix: @@ -22,11 +22,49 @@ jobs: - name: Setup Poetry uses: ./.github/actions/setup-poetry - - name: Run tests - run: make tests + - name: Run unit tests + run: poetry run pytest --cov=pinecone --timeout=120 tests/unit - - name: Build Python client - run: make package + units-grpc: + name: Run tests (GRPC) + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8, 3.9, '3.10', 3.11] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: true + + - name: Run unit tests (GRPC) + run: poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc + + package: + name: Check packaging + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8, 3.9, '3.10', 3.11] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry - - name: Build docs - run: make docs + - name: Package + run: poetry build diff --git a/Makefile b/Makefile index 62df52dd3..3f36bbf5a 100644 --- a/Makefile +++ b/Makefile @@ -9,12 +9,14 @@ image: develop: poetry install -E grpc -tests: - @echo "Installing dependencies..." - poetry install +test-unit: @echo "Running tests..." poetry run pytest --cov=pinecone --timeout=120 tests/unit +test-grpc-unit: + @echo "Running tests..." + poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc + version: poetry version diff --git a/pinecone/__init__.py b/pinecone/__init__.py index a614ff283..fbacdaddd 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -4,9 +4,4 @@ from .config import * from .exceptions import * from .control.pinecone import Pinecone -from .data.index import * - -try: - from .data.grpc.index_grpc import * -except ImportError: - pass # ignore for non-[grpc] installations +from .data.index import * \ No newline at end of file diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 535b087e8..5b6557b09 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -14,8 +14,6 @@ from pinecone.utils import get_user_agent from pinecone.data import Index -from pinecone.data import GRPCIndex - class Pinecone: def __init__( @@ -270,6 +268,3 @@ def _get_status(self, name: str): def Index(self, name: str): index_host = self.index_host_store.get_host(self.index_api, self.config, name) return Index(api_key=self.config.API_KEY, host=index_host) - - def GRPCIndex(self, name: str): - return GRPCIndex(self.config, name) diff --git a/pinecone/data/__init__.py b/pinecone/data/__init__.py index 7d4f066ef..a43d33ac4 100644 --- a/pinecone/data/__init__.py +++ b/pinecone/data/__init__.py @@ -1,2 +1 @@ -from .index import Index -from .grpc.index_grpc import GRPCIndex \ No newline at end of file +from .index import Index \ No newline at end of file diff --git a/pinecone/data/grpc/__init__.py b/pinecone/data/grpc/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/deprecated/__init__.py b/pinecone/deprecated/__init__.py deleted file mode 100644 index f67d72268..000000000 --- a/pinecone/deprecated/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .legacy_utils import * \ No newline at end of file diff --git a/pinecone/deprecated/legacy_utils.py b/pinecone/deprecated/legacy_utils.py deleted file mode 100644 index f614f80d6..000000000 --- a/pinecone/deprecated/legacy_utils.py +++ /dev/null @@ -1,21 +0,0 @@ -import re - -try: - from google.protobuf.struct_pb2 import Struct - from google.protobuf import json_format -except Exception: - pass # ignore for non-[grpc] installations - -DNS_COMPATIBLE_REGEX = re.compile("^[a-z0-9]([a-z0-9]|[-])+[a-z0-9]$") - -def validate_dns_name(name): - if not DNS_COMPATIBLE_REGEX.match(name): - raise ValueError( - "{} is invalid - service names and node names must consist of lower case " - "alphanumeric characters or '-', start with an alphabetic character, and end with an " - "alphanumeric character (e.g. 'my-name', or 'abc-123')".format(name) - ) - - -def proto_struct_to_dict(s: "Struct") -> dict: - return json_format.MessageToDict(s) diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py new file mode 100644 index 000000000..77920733d --- /dev/null +++ b/pinecone/grpc/__init__.py @@ -0,0 +1,2 @@ +from .index_grpc import GRPCIndex +from .pinecone import Pinecone \ No newline at end of file diff --git a/pinecone/data/grpc/base.py b/pinecone/grpc/base.py similarity index 99% rename from pinecone/data/grpc/base.py rename to pinecone/grpc/base.py index 3452f5962..9dad1bbc4 100644 --- a/pinecone/data/grpc/base.py +++ b/pinecone/grpc/base.py @@ -1,7 +1,7 @@ import logging from abc import ABC, abstractmethod from functools import wraps -from typing import NamedTuple, Optional, Dict +from typing import Dict import certifi import grpc diff --git a/pinecone/data/grpc/config.py b/pinecone/grpc/config.py similarity index 100% rename from pinecone/data/grpc/config.py rename to pinecone/grpc/config.py diff --git a/pinecone/data/grpc/future.py b/pinecone/grpc/future.py similarity index 100% rename from pinecone/data/grpc/future.py rename to pinecone/grpc/future.py diff --git a/pinecone/data/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py similarity index 99% rename from pinecone/data/grpc/index_grpc.py rename to pinecone/grpc/index_grpc.py index ef6e23db0..3b4344dec 100644 --- a/pinecone/data/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -34,8 +34,8 @@ REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS, ) -from pinecone.data.grpc.base import GRPCIndexBase -from pinecone.data.grpc.future import PineconeGrpcFuture +from .base import GRPCIndexBase +from .future import PineconeGrpcFuture __all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] diff --git a/pinecone/grpc/pinecone.py b/pinecone/grpc/pinecone.py new file mode 100644 index 000000000..be7654259 --- /dev/null +++ b/pinecone/grpc/pinecone.py @@ -0,0 +1,7 @@ +from ..control.pinecone import Pinecone +from .index_grpc import GRPCIndex + +class Pinecone(Pinecone): + def Index(self, name: str): + index_host = self.index_host_store.get_host(self.index_api, self.config, name) + return GRPCIndex(api_key=self.config.API_KEY, host=index_host) diff --git a/pinecone/data/grpc/retry.py b/pinecone/grpc/retry.py similarity index 100% rename from pinecone/data/grpc/retry.py rename to pinecone/grpc/retry.py diff --git a/pinecone/data/grpc/utils.py b/pinecone/grpc/utils.py similarity index 100% rename from pinecone/data/grpc/utils.py rename to pinecone/grpc/utils.py diff --git a/poetry.lock b/poetry.lock index 90b7fb33a..7c344445c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -236,7 +236,7 @@ wmi = ["wmi (>=1.5.1,<2.0.0)"] name = "googleapis-common-protos" version = "1.60.0" description = "Common protobufs used in Google APIs" -optional = false +optional = true python-versions = ">=3.7" files = [ {file = "googleapis-common-protos-1.60.0.tar.gz", hash = "sha256:e73ebb404098db405ba95d1e1ae0aa91c3e15a71da031a2eeb6b2e23e7bc3708"}, @@ -253,7 +253,7 @@ grpc = ["grpcio (>=1.44.0,<2.0.0.dev0)"] name = "grpc-gateway-protoc-gen-openapiv2" version = "0.1.0" description = "Provides the missing pieces for gRPC Gateway." -optional = false +optional = true python-versions = ">=3.6" files = [ {file = "grpc-gateway-protoc-gen-openapiv2-0.1.0.tar.gz", hash = "sha256:03b8934080ae81f709af041e4f89694db586a95ff35abba05d033d499811d4f6"}, @@ -267,7 +267,7 @@ googleapis-common-protos = "*" name = "grpcio" version = "1.59.0" description = "HTTP/2-based RPC framework" -optional = false +optional = true python-versions = ">=3.7" files = [ {file = "grpcio-1.59.0-cp310-cp310-linux_armv7l.whl", hash = "sha256:225e5fa61c35eeaebb4e7491cd2d768cd8eb6ed00f2664fa83a58f29418b39fd"}, @@ -390,7 +390,7 @@ dev = ["Sphinx (>=2.2.1)", "black (>=19.10b0)", "codecov (>=2.0.15)", "colorama name = "lz4" version = "4.3.2" description = "LZ4 Bindings for Python" -optional = false +optional = true python-versions = ">=3.7" files = [ {file = "lz4-4.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1c4c100d99eed7c08d4e8852dd11e7d1ec47a3340f49e3a96f8dfbba17ffb300"}, @@ -657,7 +657,7 @@ dev = ["pre-commit", "tox"] name = "protobuf" version = "3.20.3" description = "Protocol Buffers" -optional = false +optional = true python-versions = ">=3.7" files = [ {file = "protobuf-3.20.3-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:f4bd856d702e5b0d96a00ec6b307b0f51c1982c2bf9c0052cf9019e9a544ba99"}, @@ -1050,4 +1050,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "eb925f93e12e47feb53591724acc3a48b1f33d913798f610ce6506bda52aa38c" +content-hash = "de52f73dfd853e443fe764680dd9953775276f842470786873c3449457089cf9" diff --git a/pyproject.toml b/pyproject.toml index 24bf7617a..47d791ba2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,11 +63,11 @@ dnspython = ">=2.0.0" python-dateutil = ">=2.5.3" urllib3 = "1.25.3" tqdm = ">=4.64.1" -grpcio = ">=1.44.0" -grpc-gateway-protoc-gen-openapiv2 = "0.1.0" -googleapis-common-protos = ">=1.53.0" -lz4 = ">=3.1.3" -protobuf = "~=3.20.0" +grpcio = { version = ">=1.44.0", optional = true } +grpc-gateway-protoc-gen-openapiv2 = { version = "0.1.0", optional = true } +googleapis-common-protos = { version = ">=1.53.0", optional = true } +lz4 = { version = ">=3.1.3", optional = true } +protobuf = { version = "~=3.20.0", optional = true } [tool.poetry.group.dev.dependencies] numpy = ">=1.22" diff --git a/tests/unit/test_grpc_index.py b/tests/unit_grpc/test_grpc_index.py similarity index 99% rename from tests/unit/test_grpc_index.py rename to tests/unit_grpc/test_grpc_index.py index b98ce7687..b797fd26b 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit_grpc/test_grpc_index.py @@ -4,7 +4,8 @@ import pandas as pd import pytest -from pinecone import Config, GRPCIndex +from pinecone import Config +from pinecone.grpc import GRPCIndex from pinecone import DescribeIndexStatsRequest from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector, @@ -18,7 +19,7 @@ UpsertResponse, SparseValues, ) -from pinecone.data.grpc.utils import dict_to_proto_struct +from pinecone.grpc.utils import dict_to_proto_struct class TestGrpcIndex: def setup_method(self): From f636a791d1cb8a8bdf6e4e5b20439db61eb74824 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 6 Nov 2023 10:06:15 -0800 Subject: [PATCH 07/39] Remove unused deps (#237) ## Problem Some dependencies not being used. ## Solution Remove unused deps with `poetry remove`: - `pyyaml` - `pythondns` - `loguru` ## Type of Change - [x] Infrastructure change (CI configs, etc) --- poetry.lock | 112 +------------------------------------------------ pyproject.toml | 5 +-- 2 files changed, 2 insertions(+), 115 deletions(-) diff --git a/poetry.lock b/poetry.lock index 7c344445c..255b2a628 100644 --- a/poetry.lock +++ b/poetry.lock @@ -213,25 +213,6 @@ files = [ [package.extras] toml = ["tomli"] -[[package]] -name = "dnspython" -version = "2.4.2" -description = "DNS toolkit" -optional = false -python-versions = ">=3.8,<4.0" -files = [ - {file = "dnspython-2.4.2-py3-none-any.whl", hash = "sha256:57c6fbaaeaaf39c891292012060beb141791735dbb4004798328fc2c467402d8"}, - {file = "dnspython-2.4.2.tar.gz", hash = "sha256:8dcfae8c7460a2f84b4072e26f1c9f4101ca20c071649cb7c34e8b6a93d58984"}, -] - -[package.extras] -dnssec = ["cryptography (>=2.6,<42.0)"] -doh = ["h2 (>=4.1.0)", "httpcore (>=0.17.3)", "httpx (>=0.24.1)"] -doq = ["aioquic (>=0.9.20)"] -idna = ["idna (>=2.1,<4.0)"] -trio = ["trio (>=0.14,<0.23)"] -wmi = ["wmi (>=1.5.1,<2.0.0)"] - [[package]] name = "googleapis-common-protos" version = "1.60.0" @@ -368,24 +349,6 @@ MarkupSafe = ">=2.0" [package.extras] i18n = ["Babel (>=2.7)"] -[[package]] -name = "loguru" -version = "0.5.3" -description = "Python logging made (stupidly) simple" -optional = false -python-versions = ">=3.5" -files = [ - {file = "loguru-0.5.3-py3-none-any.whl", hash = "sha256:f8087ac396b5ee5f67c963b495d615ebbceac2796379599820e324419d53667c"}, - {file = "loguru-0.5.3.tar.gz", hash = "sha256:b28e72ac7a98be3d28ad28570299a393dfcd32e5e3f6a353dec94675767b6319"}, -] - -[package.dependencies] -colorama = {version = ">=0.3.4", markers = "sys_platform == \"win32\""} -win32-setctime = {version = ">=1.0.0", markers = "sys_platform == \"win32\""} - -[package.extras] -dev = ["Sphinx (>=2.2.1)", "black (>=19.10b0)", "codecov (>=2.0.15)", "colorama (>=0.3.4)", "flake8 (>=3.7.7)", "isort (>=5.1.1)", "pytest (>=4.6.2)", "pytest-cov (>=2.7.1)", "sphinx-autobuild (>=0.7.1)", "sphinx-rtd-theme (>=0.4.3)", "tox (>=3.9.0)", "tox-travis (>=0.12)"] - [[package]] name = "lz4" version = "4.3.2" @@ -824,65 +787,6 @@ files = [ {file = "pytz-2023.3.post1.tar.gz", hash = "sha256:7b4fddbeb94a1eba4b557da24f19fdf9db575192544270a9101d8509f9f43d7b"}, ] -[[package]] -name = "pyyaml" -version = "6.0.1" -description = "YAML parser and emitter for Python" -optional = false -python-versions = ">=3.6" -files = [ - {file = "PyYAML-6.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a"}, - {file = "PyYAML-6.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f"}, - {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"}, - {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"}, - {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"}, - {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"}, - {file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"}, - {file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"}, - {file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"}, - {file = "PyYAML-6.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab"}, - {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"}, - {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"}, - {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"}, - {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"}, - {file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"}, - {file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"}, - {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"}, - {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"}, - {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"}, - {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"}, - {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"}, - {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"}, - {file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"}, - {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"}, - {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"}, - {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd"}, - {file = "PyYAML-6.0.1-cp36-cp36m-win32.whl", hash = "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585"}, - {file = "PyYAML-6.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa"}, - {file = "PyYAML-6.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3"}, - {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27"}, - {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3"}, - {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c"}, - {file = "PyYAML-6.0.1-cp37-cp37m-win32.whl", hash = "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba"}, - {file = "PyYAML-6.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867"}, - {file = "PyYAML-6.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595"}, - {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"}, - {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"}, - {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"}, - {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"}, - {file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"}, - {file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"}, - {file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"}, - {file = "PyYAML-6.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859"}, - {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"}, - {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"}, - {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"}, - {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"}, - {file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"}, - {file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"}, - {file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"}, -] - [[package]] name = "requests" version = "2.31.0" @@ -1030,24 +934,10 @@ files = [ [package.extras] test = ["pytest (>=6.0.0)", "setuptools (>=65)"] -[[package]] -name = "win32-setctime" -version = "1.1.0" -description = "A small Python utility to set file creation time on Windows" -optional = false -python-versions = ">=3.5" -files = [ - {file = "win32_setctime-1.1.0-py3-none-any.whl", hash = "sha256:231db239e959c2fe7eb1d7dc129f11172354f98361c4fa2d6d2d7e278baa8aad"}, - {file = "win32_setctime-1.1.0.tar.gz", hash = "sha256:15cf5750465118d6929ae4de4eb46e8edae9a5634350c01ba582df868e932cb2"}, -] - -[package.extras] -dev = ["black (>=19.3b0)", "pytest (>=4.6.2)"] - [extras] grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio", "lz4", "protobuf"] [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "de52f73dfd853e443fe764680dd9953775276f842470786873c3449457089cf9" +content-hash = "fcac83995c7d0f05cfceb11f4c521c652fc5b472e3336a422a6c5404126062b9" diff --git a/pyproject.toml b/pyproject.toml index 47d791ba2..5f5ff31ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,10 +56,7 @@ classifiers=[ [tool.poetry.dependencies] python = ">=3.8,<4.0" requests = "^2.31.0" -pyyaml = ">=5.4" -loguru = "0.5.3" typing-extensions = ">=3.7.4" -dnspython = ">=2.0.0" python-dateutil = ">=2.5.3" urllib3 = "1.25.3" tqdm = ">=4.64.1" @@ -81,6 +78,7 @@ urllib3_mock = "0.3.3" responses = ">=0.8.1" pandas = ">=1.3.5" +[tool.poetry.extras] # Poetry's concept of extras is what allows us to separate the gRPC dependencies, # which will only be installed if you run `poetry install --extras "grpc"`, # from the base dependencies. @@ -88,7 +86,6 @@ pandas = ">=1.3.5" # Note that Poetry expects the dependencies to be defined in either tool.poetry.dependencies # or tool.poetry.group.dev.dependencies, but they're only referenced by name in the grpc entry under # tool.poetry.extras -[tool.poetry.extras] grpc = ["grpcio", "grpc-gateway-protoc-gen-openapiv2", "googleapis-common-protos", "lz4", "protobuf"] [build-system] From 46228c32c6b065d72ff0f971dcdadf678951f3c3 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 6 Nov 2023 14:42:52 -0800 Subject: [PATCH 08/39] [spruce] Bump to pytest 7.2.0 to fix security issue (#241) ## Problem Dependabot shows a vulnerability in one of our dev dependencies https://github.com/pinecone-io/pinecone-python-client/security/dependabot/7 ## Solution Bump to a version with the fix, pytest 7.2.0, and confirm tests still run. ## Type of Change - [x] Infrastructure change (CI configs, etc) --- poetry.lock | 66 ++++++++++++++++++++++---------------------------- pyproject.toml | 2 +- 2 files changed, 30 insertions(+), 38 deletions(-) diff --git a/poetry.lock b/poetry.lock index 255b2a628..3acf4b658 100644 --- a/poetry.lock +++ b/poetry.lock @@ -15,16 +15,6 @@ files = [ six = ">=1.6.1,<2.0" wheel = ">=0.23.0,<1.0" -[[package]] -name = "atomicwrites" -version = "1.4.1" -description = "Atomic file writes." -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "atomicwrites-1.4.1.tar.gz", hash = "sha256:81b2c9071a49367a7f770170e5eec8cb66567cfbbc8c73d20ce5ca4a8d71cf11"}, -] - [[package]] name = "attrs" version = "23.1.0" @@ -213,6 +203,20 @@ files = [ [package.extras] toml = ["tomli"] +[[package]] +name = "exceptiongroup" +version = "1.1.3" +description = "Backport of PEP 654 (exception groups)" +optional = false +python-versions = ">=3.7" +files = [ + {file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"}, + {file = "exceptiongroup-1.1.3.tar.gz", hash = "sha256:097acd85d473d75af5bb98e41b61ff7fe35efe6675e4f9370ec6ec5126d160e9"}, +] + +[package.extras] +test = ["pytest (>=6)"] + [[package]] name = "googleapis-common-protos" version = "1.60.0" @@ -647,17 +651,6 @@ files = [ {file = "protobuf-3.20.3.tar.gz", hash = "sha256:2e3427429c9cffebf259491be0af70189607f365c2f41c7c3764af6f337105f2"}, ] -[[package]] -name = "py" -version = "1.11.0" -description = "library with cross-python path, ini-parsing, io, code, log facilities" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, - {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, -] - [[package]] name = "pygments" version = "2.16.1" @@ -674,27 +667,26 @@ plugins = ["importlib-metadata"] [[package]] name = "pytest" -version = "6.2.4" +version = "7.2.0" description = "pytest: simple powerful testing with Python" optional = false -python-versions = ">=3.6" +python-versions = ">=3.7" files = [ - {file = "pytest-6.2.4-py3-none-any.whl", hash = "sha256:91ef2131a9bd6be8f76f1f08eac5c5317221d6ad1e143ae03894b862e8976890"}, - {file = "pytest-6.2.4.tar.gz", hash = "sha256:50bcad0a0b9c5a72c8e4e7c9855a3ad496ca6a881a3641b4260605450772c54b"}, + {file = "pytest-7.2.0-py3-none-any.whl", hash = "sha256:892f933d339f068883b6fd5a459f03d85bfcb355e4981e146d2c7616c21fef71"}, + {file = "pytest-7.2.0.tar.gz", hash = "sha256:c4014eb40e10f11f355ad4e3c2fb2c6c6d1919c73f3b5a433de4708202cade59"}, ] [package.dependencies] -atomicwrites = {version = ">=1.0", markers = "sys_platform == \"win32\""} attrs = ">=19.2.0" colorama = {version = "*", markers = "sys_platform == \"win32\""} +exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} iniconfig = "*" packaging = "*" -pluggy = ">=0.12,<1.0.0a1" -py = ">=1.8.2" -toml = "*" +pluggy = ">=0.12,<2.0" +tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} [package.extras] -testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "requests", "xmlschema"] +testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "xmlschema"] [[package]] name = "pytest-asyncio" @@ -838,14 +830,14 @@ files = [ ] [[package]] -name = "toml" -version = "0.10.2" -description = "Python Library for Tom's Obvious, Minimal Language" +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" optional = false -python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +python-versions = ">=3.7" files = [ - {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, - {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, ] [[package]] @@ -940,4 +932,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<4.0" -content-hash = "fcac83995c7d0f05cfceb11f4c521c652fc5b472e3336a422a6c5404126062b9" +content-hash = "e0307950e6c3594275fa15a56ec7302cce85bccc7a767d29cacb2bcc40706841" diff --git a/pyproject.toml b/pyproject.toml index 5f5ff31ec..a991bae64 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,7 +69,7 @@ protobuf = { version = "~=3.20.0", optional = true } [tool.poetry.group.dev.dependencies] numpy = ">=1.22" pdoc = "^14.1.0" -pytest = "6.2.4" +pytest = "7.2.0" pytest-asyncio = "0.15.1" pytest-cov = "2.10.1" pytest-mock = "3.6.1" From 8d66a512c5da894039574ca8080483015c5ed082 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 7 Nov 2023 14:18:54 -0500 Subject: [PATCH 09/39] Add static type checking with mypy (#240) ## Problem Some parts of this code were including typehints, but we haven't been running any checks to verify the correctness of those annotations. Static typechecking helps to improve overall quality and catch mistakes. ## Solution - Add a dev dependency on `mypy` ([site](https://mypy-lang.org/)) and packages with types for third-party dependencies. - Make adjustments throughout the code to satify the typechecker - Add steps in CI to run mypy checks automatically on every change. - For now, exclude generated code in `pinecone/core` because it has a bunch of issues but is not easy to change. Summary of code changes: - Everywhere that has a default value of `None` needs to be wrapped in the `Optional` type from the `typings` package. Correct: `def my_method(foo: Optional[str] = None)`. Incorrect: `def my_method(foo: str = None)` - Refactored config-related stuff a bit because having config classes with inner `_config` attributes seemed like a smell and also made typing config-related stuff more challening. Ended up converting what was previously the `Config` class into a `ConfigBuilder` and the actual config object is now just a `NamedTuple` which is a container for immutable data. - Mypy doesn't like when you overwrite variables in a way that changes the type. So some places required me to introduce an additional intermediate variable to satisfy the type checker. - Mypy got mad about having a `Pinecone` class in both `pinecone` and `pinecone.grpc`. So I renamed the GRPC one to `PineconeGRPC`. ## Type of Change - [x] Infrastructure change (CI configs, etc) ## Test Plan See new step running in CI. --- .github/actions/setup-poetry/action.yml | 1 + .github/workflows/testing.yaml | 15 + Makefile | 3 + pinecone/config/__init__.py | 2 +- pinecone/config/config.py | 49 +- pinecone/config/openapi.py | 5 +- pinecone/config/pinecone_config.py | 10 +- pinecone/control/index_host_store.py | 5 +- pinecone/control/pinecone.py | 34 +- pinecone/data/index.py | 17 +- pinecone/data/vector_factory.py | 2 +- pinecone/grpc/__init__.py | 2 +- pinecone/grpc/base.py | 12 +- pinecone/grpc/config.py | 2 +- pinecone/grpc/index_grpc.py | 61 +- pinecone/grpc/pinecone.py | 6 +- pinecone/grpc/utils.py | 26 +- pinecone/utils/deprecation_notice.py | 3 +- poetry.lock | 836 +++++++++++++++--------- pyproject.toml | 18 +- tests/unit/test_config.py | 32 +- 21 files changed, 689 insertions(+), 452 deletions(-) diff --git a/.github/actions/setup-poetry/action.yml b/.github/actions/setup-poetry/action.yml index 1b8f6e1b9..a60b6a1c2 100644 --- a/.github/actions/setup-poetry/action.yml +++ b/.github/actions/setup-poetry/action.yml @@ -5,6 +5,7 @@ inputs: description: 'Install gRPC dependencies' required: true default: 'false' + runs: using: 'composite' steps: diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index bf3c599c4..678ad8760 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -24,6 +24,13 @@ jobs: - name: Run unit tests run: poetry run pytest --cov=pinecone --timeout=120 tests/unit + + - name: mypy check + run: | + # Still lots of errors when running on the whole package (especially + # in the generated core module), but we can check these subpackages + # so we don't add new regressions. + poetry run mypy pinecone --exclude pinecone/core --exclude pinecone/grpc units-grpc: name: Run tests (GRPC) @@ -48,6 +55,14 @@ jobs: - name: Run unit tests (GRPC) run: poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc + - name: mypy check + run: | + # Still lots of errors when running on the whole package (especially + # in the generated core module), but we can check these subpackages + # so we don't add new regressions. + poetry run mypy pinecone --exclude pinecone/core + + package: name: Check packaging runs-on: ubuntu-latest diff --git a/Makefile b/Makefile index 3f36bbf5a..45e13cefc 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,9 @@ test-grpc-unit: @echo "Running tests..." poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc +make type-check: + poetry run mypy pinecone --exclude pinecone/core + version: poetry version diff --git a/pinecone/config/__init__.py b/pinecone/config/__init__.py index 42784d1ed..f6b039009 100644 --- a/pinecone/config/__init__.py +++ b/pinecone/config/__init__.py @@ -1,2 +1,2 @@ -from .config import Config +from .config import ConfigBuilder, Config from .pinecone_config import PineconeConfig diff --git a/pinecone/config/config.py b/pinecone/config/config.py index 886d01b5e..0b31e10f3 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -1,20 +1,19 @@ -from typing import NamedTuple +from typing import NamedTuple, Optional import os -from pinecone.utils import check_kwargs from pinecone.exceptions import PineconeConfigurationError from pinecone.core.client.exceptions import ApiKeyError from pinecone.config.openapi import OpenApiConfigFactory from pinecone.core.client.configuration import Configuration as OpenApiConfiguration -class ConfigBase(NamedTuple): +class Config(NamedTuple): api_key: str = "" host: str = "" - openapi_config: OpenApiConfiguration = None + openapi_config: Optional[OpenApiConfiguration] = None -class Config: +class ConfigBuilder: """ Configurations are resolved in the following order: @@ -31,39 +30,25 @@ class Config: :param openapi_config: Optional. Set OpenAPI client configuration. """ - def __init__( - self, - api_key: str = None, - host: str = None, - openapi_config: OpenApiConfiguration = None, + @staticmethod + def build( + api_key: Optional[str] = None, + host: Optional[str] = None, + openapi_config: Optional[OpenApiConfiguration] = None, **kwargs, - ): + ) -> Config: api_key = api_key or kwargs.pop("api_key", None) or os.getenv("PINECONE_API_KEY") host = host or kwargs.pop("host", None) + + if not api_key: + raise PineconeConfigurationError("You haven't specified an Api-Key.") + if not host: + raise PineconeConfigurationError("You haven't specified a host.") + openapi_config = ( openapi_config or kwargs.pop("openapi_config", None) or OpenApiConfigFactory.build(api_key=api_key, host=host) ) - check_kwargs(self.__init__, kwargs) - self._config = ConfigBase(api_key, host, openapi_config) - self.validate() - - def validate(self): - if not self._config.api_key: - raise PineconeConfigurationError("You haven't specified an Api-Key.") - if not self._config.host: - raise PineconeConfigurationError("You haven't specified a host.") - - @property - def API_KEY(self): - return self._config.api_key - - @property - def HOST(self): - return self._config.host - - @property - def OPENAPI_CONFIG(self): - return self._config.openapi_config + return Config(api_key, host, openapi_config) \ No newline at end of file diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index 83f9a9cca..cca504bc1 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -1,5 +1,5 @@ import sys -from typing import List +from typing import List, Optional import certifi import requests @@ -16,7 +16,7 @@ class OpenApiConfigFactory: @classmethod - def build(cls, api_key: str, host: str = None, **kwargs): + def build(cls, api_key: str, host: Optional[str] = None, **kwargs): openapi_config = OpenApiConfiguration() openapi_config.host = host openapi_config.ssl_ca_cert = certifi.where() @@ -26,6 +26,7 @@ def build(cls, api_key: str, host: str = None, **kwargs): @classmethod def _get_socket_options( + self, do_keep_alive: bool = True, keep_alive_idle_sec: int = TCP_KEEPIDLE, keep_alive_interval_sec: int = TCP_KEEPINTVL, diff --git a/pinecone/config/pinecone_config.py b/pinecone/config/pinecone_config.py index 64f879a81..024431ed8 100644 --- a/pinecone/config/pinecone_config.py +++ b/pinecone/config/pinecone_config.py @@ -1,10 +1,12 @@ +from typing import Optional import os -from .config import Config +from .config import ConfigBuilder, Config DEFAULT_CONTROLLER_HOST = "https://api.pinecone.io" -class PineconeConfig(Config): - def __init__(self, api_key: str = None, host: str = None, **kwargs): +class PineconeConfig(): + @staticmethod + def build(api_key: Optional[str] = None, host: Optional[str] = None, **kwargs) -> Config: host = host or kwargs.get("host") or os.getenv("PINECONE_CONTROLLER_HOST") or DEFAULT_CONTROLLER_HOST - super().__init__(api_key=api_key, host=host, **kwargs) + return ConfigBuilder.build(api_key=api_key, host=host, **kwargs) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index efe9ea5d4..dc15a0a92 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,9 +1,10 @@ +from typing import Dict from pinecone.config import Config from pinecone.core.client.api.index_operations_api import IndexOperationsApi class SingletonMeta(type): - _instances = {} + _instances: Dict[str, str] = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: @@ -17,7 +18,7 @@ def __init__(self): self._indexHosts = {} def _key(self, config: Config, index_name: str) -> str: - return ":".join([config.API_KEY, index_name]) + return ":".join([config.api_key, index_name]) def delete_host(self, config: Config, index_name: str): key = self._key(config, index_name) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 5b6557b09..7f95bff3d 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -1,5 +1,5 @@ import time -from typing import Optional +from typing import Optional, Dict, Any, cast from .index_host_store import IndexHostStore @@ -18,21 +18,25 @@ class Pinecone: def __init__( self, - api_key: str = None, - host: str = None, - config: Config = None, - index_api: IndexOperationsApi = None, + api_key: Optional[str] = None, + host: Optional[str] = None, + config: Optional[Config] = None, + index_api: Optional[IndexOperationsApi] = None, **kwargs, ): if config or kwargs.get("config"): - self.config = config or kwargs.get("config") + configKwarg = config or kwargs.get("config") + if not isinstance(configKwarg, Config): + raise TypeError("config must be of type pinecone.config.Config") + else: + self.config = configKwarg else: - self.config = PineconeConfig(api_key=api_key, host=host, **kwargs) - + self.config = PineconeConfig.build(api_key=api_key, host=host, **kwargs) + if index_api: self.index_api = index_api else: - api_client = ApiClient(configuration=self.config.OPENAPI_CONFIG) + api_client = ApiClient(configuration=self.config.openapi_config) api_client.user_agent = get_user_agent() self.index_api = IndexOperationsApi(api_client) @@ -45,15 +49,15 @@ def create_index( cloud: str, region: str, capacity_mode: str, - timeout: int = None, + timeout: Optional[int] = None, index_type: str = "approximated", metric: str = "cosine", replicas: int = 1, shards: int = 1, pods: int = 1, pod_type: str = "p1", - index_config: dict = None, - metadata_config: dict = None, + index_config: Optional[dict] = None, + metadata_config: Optional[dict] = None, source_collection: str = "", ): """Creates a Pinecone index. @@ -138,7 +142,7 @@ def is_ready(): ) ) - def delete_index(self, name: str, timeout: int = None): + def delete_index(self, name: str, timeout: Optional[int] = None): """Deletes a Pinecone index. :param name: the name of the index. @@ -210,7 +214,7 @@ def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: O :param: pod_type: the new pod_type for the index. """ api_instance = self.index_api - config_args = {} + config_args: Dict[str, Any] = {} if pod_type != "": config_args.update(pod_type=pod_type) if replicas: @@ -267,4 +271,4 @@ def _get_status(self, name: str): def Index(self, name: str): index_host = self.index_host_store.get_host(self.index_api, self.config, name) - return Index(api_key=self.config.API_KEY, host=index_host) + return Index(api_key=self.config.api_key, host=index_host) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 1b8e70f01..074365f74 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -3,7 +3,7 @@ from collections.abc import Iterable from typing import Union, List, Tuple, Optional, Dict, Any -from pinecone.config import Config +from pinecone.config import ConfigBuilder from pinecone.core.client.models import SparseValues from pinecone.core.client import ApiClient @@ -76,13 +76,13 @@ class Index(): """ def __init__(self, api_key: str, host: str, pool_threads=1, **kwargs): - api_key = api_key or kwargs.get("api_key") - host = host or kwargs.get('host') + api_key = api_key or kwargs.get("api_key", None) + host = host or kwargs.get('host', None) pool_threads = pool_threads or kwargs.get("pool_threads") - self._config = Config(api_key=api_key, host=host, **kwargs) + self._config = ConfigBuilder.build(api_key=api_key, host=host, **kwargs) - api_client = ApiClient(configuration=self._config.OPENAPI_CONFIG, pool_threads=pool_threads) + api_client = ApiClient(configuration=self._config.openapi_config, pool_threads=pool_threads) api_client.user_agent = get_user_agent() self._api_client = api_client self._vector_api = VectorOperationsApi(api_client=api_client) @@ -180,7 +180,7 @@ def upsert( return UpsertResponse(upserted_count=total_upserted) def _upsert_batch( - self, vectors: List[Vector], namespace: Optional[str], _check_type: bool, **kwargs + self, vectors: Union[List[Vector], List[tuple], List[dict]], namespace: Optional[str], _check_type: bool, **kwargs ) -> UpsertResponse: args_dict = self._parse_non_empty_args([("namespace", namespace)]) vec_builder = lambda v: VectorFactory.build(v, check_type=_check_type) @@ -202,7 +202,7 @@ def _iter_dataframe(df, batch_size): yield batch def upsert_from_dataframe( - self, df, namespace: str = None, batch_size: int = 500, show_progress: bool = True + self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True ) -> UpsertResponse: """Upserts a dataframe into the index. @@ -416,7 +416,8 @@ def _query_transform(item): ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}, ) - return parse_query_response(response, vector is not None or id) + unary_query = True if vector is not None or id else False + return parse_query_response(response, unary_query) @validate_and_convert_errors def update( diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index 831df4f12..0b38a8ca9 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -91,7 +91,7 @@ def _dict_to_vector(item, check_type: bool) -> Vector: try: return Vector(**item, _check_type=check_type) except TypeError as e: - if not isinstance(item["values"], Iterable) or not isinstance(item["values"][0], numbers.Real): + if not isinstance(item["values"], Iterable) or not isinstance(item["values"].__iter__().__next__(), numbers.Real): raise TypeError(f"Column `values` is expected to be a list of floats") raise e diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py index 77920733d..5ba565ce8 100644 --- a/pinecone/grpc/__init__.py +++ b/pinecone/grpc/__init__.py @@ -1,2 +1,2 @@ from .index_grpc import GRPCIndex -from .pinecone import Pinecone \ No newline at end of file +from .pinecone import PineconeGRPC \ No newline at end of file diff --git a/pinecone/grpc/base.py b/pinecone/grpc/base.py index 9dad1bbc4..6b6ee641c 100644 --- a/pinecone/grpc/base.py +++ b/pinecone/grpc/base.py @@ -1,11 +1,11 @@ import logging from abc import ABC, abstractmethod from functools import wraps -from typing import Dict +from typing import Dict, Optional import certifi import grpc -from grpc._channel import _InactiveRpcError +from grpc._channel import _InactiveRpcError, Channel import json from .retry import RetryConfig @@ -29,15 +29,15 @@ def __init__( self, index_name: str, config: Config, - channel=None, - grpc_config: GRPCClientConfig = None, - _endpoint_override: str = None, + channel: Optional[Channel] =None, + grpc_config: Optional[GRPCClientConfig] = None, + _endpoint_override: Optional[str] = None, ): self.name = index_name self.grpc_client_config = grpc_config or GRPCClientConfig() self.retry_config = self.grpc_client_config.retry_config or RetryConfig() - self.fixed_metadata = {"api-key": config.API_KEY, "service-name": index_name, "client-version": CLIENT_VERSION} + self.fixed_metadata = {"api-key": config.api_key, "service-name": index_name, "client-version": CLIENT_VERSION} self._endpoint_override = _endpoint_override self.method_config = json.dumps( diff --git a/pinecone/grpc/config.py b/pinecone/grpc/config.py index 13ab7dae3..1a58cd6a5 100644 --- a/pinecone/grpc/config.py +++ b/pinecone/grpc/config.py @@ -25,7 +25,7 @@ class GRPCClientConfig(NamedTuple): conn_timeout: int = 1 reuse_channel: bool = True retry_config: Optional[RetryConfig] = None - grpc_channel_options: Dict[str, str] = None + grpc_channel_options: Optional[Dict[str, str]] = None @classmethod def _from_dict(cls, kwargs: dict): diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index 3b4344dec..47c9d3aac 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -1,6 +1,6 @@ import logging import numbers -from typing import Optional, Dict, Iterable, Union, List, Tuple, Any +from typing import Optional, Dict, Iterable, Union, List, Tuple, Any, TypedDict, cast from collections.abc import Mapping from google.protobuf import json_format @@ -41,6 +41,10 @@ _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.""" @@ -119,7 +123,7 @@ def upsert( "https://docs.pinecone.io/docs/performance-tuning" ) - def _dict_to_grpc_vector(item): + def _dict_to_grpc_vector(item) -> GRPCVector: item_keys = set(item.keys()) if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): raise ValueError( @@ -150,7 +154,7 @@ def _dict_to_grpc_vector(item): ) from e metadata = item.get("metadata", None) - if metadata is not None and not isinstance(metadata, Mapping): + if metadata is not None and not isinstance(metadata, Dict): raise TypeError(f"Column `metadata` is expected to be a dictionary, found {type(metadata)}") try: @@ -163,11 +167,11 @@ def _dict_to_grpc_vector(item): except TypeError as e: # No need to raise a dedicated error for `id` - protobuf's error message is clear enough - if not isinstance(item["values"], Iterable) or not isinstance(item["values"][0], numbers.Real): + if not isinstance(item["values"], Iterable) or not isinstance(item["values"].__iter__().__next__(), numbers.Real): raise TypeError(f"Column `values` is expected to be a list of floats") raise - def _vector_transform(item): + def _vector_transform(item) -> GRPCVector: if isinstance(item, GRPCVector): return item elif isinstance(item, tuple): @@ -178,7 +182,7 @@ def _vector_transform(item): f"To pass sparse values please use either dicts or GRPCVector objects as inputs." ) id, values, metadata = fix_tuple_length(item, 3) - return GRPCVector(id=id, values=values, metadata=dict_to_proto_struct(metadata) or {}) + return GRPCVector(id=id, values=values, metadata=dict_to_proto_struct(metadata)) elif isinstance(item, Mapping): return _dict_to_grpc_vector(item) raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") @@ -218,11 +222,11 @@ def _upsert_batch( def upsert_from_dataframe( self, df, - namespace: str = None, + namespace: str = "", batch_size: int = 500, use_async_requests: bool = True, show_progress: bool = True, - ) -> None: + ) -> UpsertResponse: """Upserts a dataframe into the index. Args: @@ -251,11 +255,13 @@ def upsert_from_dataframe( results.append(res) if use_async_requests: - results = [async_result.result() for async_result in tqdm(results, desc="collecting async responses")] + cast_results = cast(List[PineconeGrpcFuture], results) + results = [async_result.result() for async_result in tqdm(cast_results, desc="collecting async responses")] upserted_count = 0 for res in results: - upserted_count += res.upserted_count + if hasattr(res, 'upserted_count') and isinstance(res.upserted_count, int): + upserted_count += res.upserted_count return UpsertResponse(upserted_count=upserted_count) @@ -307,10 +313,12 @@ def delete( """ if filter is not None: - filter = dict_to_proto_struct(filter) + filter_struct = dict_to_proto_struct(filter) + else: + filter_struct = None args_dict = self._parse_non_empty_args( - [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter)] + [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter_struct)] ) timeout = kwargs.pop("timeout", None) @@ -356,7 +364,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[GRPCSparseValues, Dict[str, Union[List[float], List[int]]]]] = None, + sparse_vector: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> QueryResponse: """ @@ -415,7 +423,9 @@ def _query_transform(item): queries = list(map(_query_transform, queries)) if queries is not None else None if filter is not None: - filter = dict_to_proto_struct(filter) + filter_struct = dict_to_proto_struct(filter) + else: + filter_struct = None sparse_vector = self._parse_sparse_values_arg(sparse_vector) args_dict = self._parse_non_empty_args( @@ -425,7 +435,7 @@ def _query_transform(item): ("queries", queries), ("namespace", namespace), ("top_k", top_k), - ("filter", filter), + ("filter", filter_struct), ("include_values", include_values), ("include_metadata", include_metadata), ("sparse_vector", sparse_vector), @@ -437,7 +447,8 @@ def _query_transform(item): timeout = kwargs.pop("timeout", None) response = self._wrap_grpc_call(self.stub.Query, request, timeout=timeout) json_response = json_format.MessageToDict(response) - return parse_query_response(json_response, vector is not None or id, _check_type=False) + unary_query = True if vector is not None or id else False + return parse_query_response(json_response, unary_query, _check_type=False) def update( self, @@ -446,7 +457,7 @@ def update( values: Optional[List[float]] = None, set_metadata: Optional[Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, namespace: Optional[str] = None, - sparse_values: Optional[Union[GRPCSparseValues, Dict[str, Union[List[float], List[int]]]]] = None, + sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, **kwargs, ) -> Union[UpdateResponse, PineconeGrpcFuture]: """ @@ -479,14 +490,16 @@ def update( Returns: UpdateResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. """ if set_metadata is not None: - set_metadata = dict_to_proto_struct(set_metadata) - timeout = kwargs.pop("timeout", None) + set_metadata_struct = dict_to_proto_struct(set_metadata) + else: + set_metadata_struct = None + timeout = kwargs.pop("timeout", None) sparse_values = self._parse_sparse_values_arg(sparse_values) args_dict = self._parse_non_empty_args( [ ("values", values), - ("set_metadata", set_metadata), + ("set_metadata", set_metadata_struct), ("namespace", namespace), ("sparse_values", sparse_values), ] @@ -518,8 +531,10 @@ def describe_index_stats( Returns: DescribeIndexStatsResponse object which contains stats about the index. """ if filter is not None: - filter = dict_to_proto_struct(filter) - args_dict = self._parse_non_empty_args([("filter", filter)]) + filter_struct = dict_to_proto_struct(filter) + else: + filter_struct = None + args_dict = self._parse_non_empty_args([("filter", filter_struct)]) timeout = kwargs.pop("timeout", None) request = DescribeIndexStatsRequest(**args_dict) @@ -533,7 +548,7 @@ def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: @staticmethod def _parse_sparse_values_arg( - sparse_values: Optional[Union[GRPCSparseValues, Dict[str, Union[List[float], List[int]]]]] + sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] ) -> Optional[GRPCSparseValues]: if sparse_values is None: return None diff --git a/pinecone/grpc/pinecone.py b/pinecone/grpc/pinecone.py index be7654259..87ecf871d 100644 --- a/pinecone/grpc/pinecone.py +++ b/pinecone/grpc/pinecone.py @@ -1,7 +1,9 @@ from ..control.pinecone import Pinecone +from ..config.config import ConfigBuilder from .index_grpc import GRPCIndex -class Pinecone(Pinecone): +class PineconeGRPC(Pinecone): def Index(self, name: str): index_host = self.index_host_store.get_host(self.index_api, self.config, name) - return GRPCIndex(api_key=self.config.API_KEY, host=index_host) + config = ConfigBuilder.build(api_key=self.config.api_key, host=index_host) + return GRPCIndex(index_name=name, config=config) diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index fc69c83e5..4e8057ecd 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -13,10 +13,18 @@ NamespaceSummary, ) +from typing import NamedTuple, Optional + +class QueryResponseKwargs(NamedTuple): + check_type: bool + namespace: Optional[str] + matches: Optional[list] + results: Optional[list] + def _generate_request_id() -> str: return str(uuid.uuid4()) -def dict_to_proto_struct(d: dict) -> "Struct": +def dict_to_proto_struct(d: Optional[dict]) -> "Struct": if not d: d = {} s = Struct() @@ -80,13 +88,19 @@ def parse_query_response(response: dict, unary_query: bool, _check_type: bool = ) m.append(sc) - kwargs = {"_check_type": _check_type} if unary_query: - kwargs["namespace"] = response.get("namespace", "") - kwargs["matches"] = m + namespace = response.get("namespace", "") + matches = m + results = [] else: - kwargs["results"] = res - return QueryResponse(**kwargs) + namespace = "" + matches = [] + results = res + + kw = QueryResponseKwargs(_check_type, namespace, matches, results) + kw_dict = kw._asdict() + kw_dict["_check_type"] = kw.check_type + return QueryResponse(**kw._asdict()) def parse_stats_response(response: dict): diff --git a/pinecone/utils/deprecation_notice.py b/pinecone/utils/deprecation_notice.py index a27fe9c57..bc86a08c0 100644 --- a/pinecone/utils/deprecation_notice.py +++ b/pinecone/utils/deprecation_notice.py @@ -1,5 +1,6 @@ +from typing import Optional import warnings -def warn_deprecated(description: str = "", deprecated_in: str = None, removal_in: str = None): +def warn_deprecated(description: str, deprecated_in: str, removal_in: str): message = f"DEPRECATED since v{deprecated_in} [Will be removed in v{removal_in}]: {description}" warnings.warn(message, FutureWarning) \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index 3acf4b658..1aa020069 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,20 +1,5 @@ # This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. -[[package]] -name = "astunparse" -version = "1.6.3" -description = "An AST unparser for Python" -optional = false -python-versions = "*" -files = [ - {file = "astunparse-1.6.3-py2.py3-none-any.whl", hash = "sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8"}, - {file = "astunparse-1.6.3.tar.gz", hash = "sha256:5ad93a8456f0d084c3456d059fd9a92cce667963232cbf763eac3bc5b7940872"}, -] - -[package.dependencies] -six = ">=1.6.1,<2.0" -wheel = ">=0.23.0,<1.0" - [[package]] name = "attrs" version = "23.1.0" @@ -46,86 +31,101 @@ files = [ [[package]] name = "charset-normalizer" -version = "3.2.0" +version = "3.3.2" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." optional = false python-versions = ">=3.7.0" files = [ - {file = "charset-normalizer-3.2.0.tar.gz", hash = "sha256:3bb3d25a8e6c0aedd251753a79ae98a093c7e7b471faa3aa9a93a81431987ace"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0b87549028f680ca955556e3bd57013ab47474c3124dc069faa0b6545b6c9710"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7c70087bfee18a42b4040bb9ec1ca15a08242cf5867c58726530bdf3945672ed"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a103b3a7069b62f5d4890ae1b8f0597618f628b286b03d4bc9195230b154bfa9"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:94aea8eff76ee6d1cdacb07dd2123a68283cb5569e0250feab1240058f53b623"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:db901e2ac34c931d73054d9797383d0f8009991e723dab15109740a63e7f902a"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b0dac0ff919ba34d4df1b6131f59ce95b08b9065233446be7e459f95554c0dc8"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:193cbc708ea3aca45e7221ae58f0fd63f933753a9bfb498a3b474878f12caaad"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:09393e1b2a9461950b1c9a45d5fd251dc7c6f228acab64da1c9c0165d9c7765c"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:baacc6aee0b2ef6f3d308e197b5d7a81c0e70b06beae1f1fcacffdbd124fe0e3"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:bf420121d4c8dce6b889f0e8e4ec0ca34b7f40186203f06a946fa0276ba54029"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:c04a46716adde8d927adb9457bbe39cf473e1e2c2f5d0a16ceb837e5d841ad4f"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:aaf63899c94de41fe3cf934601b0f7ccb6b428c6e4eeb80da72c58eab077b19a"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:d62e51710986674142526ab9f78663ca2b0726066ae26b78b22e0f5e571238dd"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-win32.whl", hash = "sha256:04e57ab9fbf9607b77f7d057974694b4f6b142da9ed4a199859d9d4d5c63fe96"}, - {file = "charset_normalizer-3.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:48021783bdf96e3d6de03a6e39a1171ed5bd7e8bb93fc84cc649d11490f87cea"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4957669ef390f0e6719db3613ab3a7631e68424604a7b448f079bee145da6e09"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:46fb8c61d794b78ec7134a715a3e564aafc8f6b5e338417cb19fe9f57a5a9bf2"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f779d3ad205f108d14e99bb3859aa7dd8e9c68874617c72354d7ecaec2a054ac"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f25c229a6ba38a35ae6e25ca1264621cc25d4d38dca2942a7fce0b67a4efe918"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2efb1bd13885392adfda4614c33d3b68dee4921fd0ac1d3988f8cbb7d589e72a"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1f30b48dd7fa1474554b0b0f3fdfdd4c13b5c737a3c6284d3cdc424ec0ffff3a"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:246de67b99b6851627d945db38147d1b209a899311b1305dd84916f2b88526c6"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9bd9b3b31adcb054116447ea22caa61a285d92e94d710aa5ec97992ff5eb7cf3"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:8c2f5e83493748286002f9369f3e6607c565a6a90425a3a1fef5ae32a36d749d"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:3170c9399da12c9dc66366e9d14da8bf7147e1e9d9ea566067bbce7bb74bd9c2"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:7a4826ad2bd6b07ca615c74ab91f32f6c96d08f6fcc3902ceeedaec8cdc3bcd6"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:3b1613dd5aee995ec6d4c69f00378bbd07614702a315a2cf6c1d21461fe17c23"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9e608aafdb55eb9f255034709e20d5a83b6d60c054df0802fa9c9883d0a937aa"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-win32.whl", hash = "sha256:f2a1d0fd4242bd8643ce6f98927cf9c04540af6efa92323e9d3124f57727bfc1"}, - {file = "charset_normalizer-3.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:681eb3d7e02e3c3655d1b16059fbfb605ac464c834a0c629048a30fad2b27489"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c57921cda3a80d0f2b8aec7e25c8aa14479ea92b5b51b6876d975d925a2ea346"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:41b25eaa7d15909cf3ac4c96088c1f266a9a93ec44f87f1d13d4a0e86c81b982"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f058f6963fd82eb143c692cecdc89e075fa0828db2e5b291070485390b2f1c9c"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a7647ebdfb9682b7bb97e2a5e7cb6ae735b1c25008a70b906aecca294ee96cf4"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eef9df1eefada2c09a5e7a40991b9fc6ac6ef20b1372abd48d2794a316dc0449"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e03b8895a6990c9ab2cdcd0f2fe44088ca1c65ae592b8f795c3294af00a461c3"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:ee4006268ed33370957f55bf2e6f4d263eaf4dc3cfc473d1d90baff6ed36ce4a"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:c4983bf937209c57240cff65906b18bb35e64ae872da6a0db937d7b4af845dd7"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:3bb7fda7260735efe66d5107fb7e6af6a7c04c7fce9b2514e04b7a74b06bf5dd"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:72814c01533f51d68702802d74f77ea026b5ec52793c791e2da806a3844a46c3"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:70c610f6cbe4b9fce272c407dd9d07e33e6bf7b4aa1b7ffb6f6ded8e634e3592"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-win32.whl", hash = "sha256:a401b4598e5d3f4a9a811f3daf42ee2291790c7f9d74b18d75d6e21dda98a1a1"}, - {file = "charset_normalizer-3.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:c0b21078a4b56965e2b12f247467b234734491897e99c1d51cee628da9786959"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:95eb302ff792e12aba9a8b8f8474ab229a83c103d74a750ec0bd1c1eea32e669"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1a100c6d595a7f316f1b6f01d20815d916e75ff98c27a01ae817439ea7726329"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:6339d047dab2780cc6220f46306628e04d9750f02f983ddb37439ca47ced7149"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e4b749b9cc6ee664a3300bb3a273c1ca8068c46be705b6c31cf5d276f8628a94"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a38856a971c602f98472050165cea2cdc97709240373041b69030be15047691f"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f87f746ee241d30d6ed93969de31e5ffd09a2961a051e60ae6bddde9ec3583aa"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:89f1b185a01fe560bc8ae5f619e924407efca2191b56ce749ec84982fc59a32a"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1c8a2f4c69e08e89632defbfabec2feb8a8d99edc9f89ce33c4b9e36ab63037"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:2f4ac36d8e2b4cc1aa71df3dd84ff8efbe3bfb97ac41242fbcfc053c67434f46"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:a386ebe437176aab38c041de1260cd3ea459c6ce5263594399880bbc398225b2"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:ccd16eb18a849fd8dcb23e23380e2f0a354e8daa0c984b8a732d9cfaba3a776d"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:e6a5bf2cba5ae1bb80b154ed68a3cfa2fa00fde979a7f50d6598d3e17d9ac20c"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:45de3f87179c1823e6d9e32156fb14c1927fcc9aba21433f088fdfb555b77c10"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-win32.whl", hash = "sha256:1000fba1057b92a65daec275aec30586c3de2401ccdcd41f8a5c1e2c87078706"}, - {file = "charset_normalizer-3.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:8b2c760cfc7042b27ebdb4a43a4453bd829a5742503599144d54a032c5dc7e9e"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:855eafa5d5a2034b4621c74925d89c5efef61418570e5ef9b37717d9c796419c"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:203f0c8871d5a7987be20c72442488a0b8cfd0f43b7973771640fc593f56321f"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e857a2232ba53ae940d3456f7533ce6ca98b81917d47adc3c7fd55dad8fab858"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5e86d77b090dbddbe78867a0275cb4df08ea195e660f1f7f13435a4649e954e5"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c4fb39a81950ec280984b3a44f5bd12819953dc5fa3a7e6fa7a80db5ee853952"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2dee8e57f052ef5353cf608e0b4c871aee320dd1b87d351c28764fc0ca55f9f4"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8700f06d0ce6f128de3ccdbc1acaea1ee264d2caa9ca05daaf492fde7c2a7200"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1920d4ff15ce893210c1f0c0e9d19bfbecb7983c76b33f046c13a8ffbd570252"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:c1c76a1743432b4b60ab3358c937a3fe1341c828ae6194108a94c69028247f22"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f7560358a6811e52e9c4d142d497f1a6e10103d3a6881f18d04dbce3729c0e2c"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:c8063cf17b19661471ecbdb3df1c84f24ad2e389e326ccaf89e3fb2484d8dd7e"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:cd6dbe0238f7743d0efe563ab46294f54f9bc8f4b9bcf57c3c666cc5bc9d1299"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1249cbbf3d3b04902ff081ffbb33ce3377fa6e4c7356f759f3cd076cc138d020"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-win32.whl", hash = "sha256:6c409c0deba34f147f77efaa67b8e4bb83d2f11c8806405f76397ae5b8c0d1c9"}, - {file = "charset_normalizer-3.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:7095f6fbfaa55defb6b733cfeb14efaae7a29f0b59d8cf213be4e7ca0b857b80"}, - {file = "charset_normalizer-3.2.0-py3-none-any.whl", hash = "sha256:8e098148dd37b4ce3baca71fb394c81dc5d9c7728c95df695d2dca218edf40e6"}, + {file = "charset-normalizer-3.3.2.tar.gz", hash = "sha256:f30c3cb33b24454a82faecaf01b19c18562b1e89558fb6c56de4d9118a032fd5"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:25baf083bf6f6b341f4121c2f3c548875ee6f5339300e08be3f2b2ba1721cdd3"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:06435b539f889b1f6f4ac1758871aae42dc3a8c0e24ac9e60c2384973ad73027"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9063e24fdb1e498ab71cb7419e24622516c4a04476b17a2dab57e8baa30d6e03"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6897af51655e3691ff853668779c7bad41579facacf5fd7253b0133308cf000d"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1d3193f4a680c64b4b6a9115943538edb896edc190f0b222e73761716519268e"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cd70574b12bb8a4d2aaa0094515df2463cb429d8536cfb6c7ce983246983e5a6"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8465322196c8b4d7ab6d1e049e4c5cb460d0394da4a27d23cc242fbf0034b6b5"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9a8e9031d613fd2009c182b69c7b2c1ef8239a0efb1df3f7c8da66d5dd3d537"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:beb58fe5cdb101e3a055192ac291b7a21e3b7ef4f67fa1d74e331a7f2124341c"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:e06ed3eb3218bc64786f7db41917d4e686cc4856944f53d5bdf83a6884432e12"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:2e81c7b9c8979ce92ed306c249d46894776a909505d8f5a4ba55b14206e3222f"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:572c3763a264ba47b3cf708a44ce965d98555f618ca42c926a9c1616d8f34269"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fd1abc0d89e30cc4e02e4064dc67fcc51bd941eb395c502aac3ec19fab46b519"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-win32.whl", hash = "sha256:3d47fa203a7bd9c5b6cee4736ee84ca03b8ef23193c0d1ca99b5089f72645c73"}, + {file = "charset_normalizer-3.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:10955842570876604d404661fbccbc9c7e684caf432c09c715ec38fbae45ae09"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:802fe99cca7457642125a8a88a084cef28ff0cf9407060f7b93dca5aa25480db"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:573f6eac48f4769d667c4442081b1794f52919e7edada77495aaed9236d13a96"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:549a3a73da901d5bc3ce8d24e0600d1fa85524c10287f6004fbab87672bf3e1e"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f27273b60488abe721a075bcca6d7f3964f9f6f067c8c4c605743023d7d3944f"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ceae2f17a9c33cb48e3263960dc5fc8005351ee19db217e9b1bb15d28c02574"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65f6f63034100ead094b8744b3b97965785388f308a64cf8d7c34f2f2e5be0c4"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:753f10e867343b4511128c6ed8c82f7bec3bd026875576dfd88483c5c73b2fd8"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4a78b2b446bd7c934f5dcedc588903fb2f5eec172f3d29e52a9096a43722adfc"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e537484df0d8f426ce2afb2d0f8e1c3d0b114b83f8850e5f2fbea0e797bd82ae"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:eb6904c354526e758fda7167b33005998fb68c46fbc10e013ca97f21ca5c8887"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:deb6be0ac38ece9ba87dea880e438f25ca3eddfac8b002a2ec3d9183a454e8ae"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4ab2fe47fae9e0f9dee8c04187ce5d09f48eabe611be8259444906793ab7cbce"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:80402cd6ee291dcb72644d6eac93785fe2c8b9cb30893c1af5b8fdd753b9d40f"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-win32.whl", hash = "sha256:7cd13a2e3ddeed6913a65e66e94b51d80a041145a026c27e6bb76c31a853c6ab"}, + {file = "charset_normalizer-3.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:663946639d296df6a2bb2aa51b60a2454ca1cb29835324c640dafb5ff2131a77"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:0b2b64d2bb6d3fb9112bafa732def486049e63de9618b5843bcdd081d8144cd8"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:ddbb2551d7e0102e7252db79ba445cdab71b26640817ab1e3e3648dad515003b"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:55086ee1064215781fff39a1af09518bc9255b50d6333f2e4c74ca09fac6a8f6"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f4a014bc36d3c57402e2977dada34f9c12300af536839dc38c0beab8878f38a"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a10af20b82360ab00827f916a6058451b723b4e65030c5a18577c8b2de5b3389"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8d756e44e94489e49571086ef83b2bb8ce311e730092d2c34ca8f7d925cb20aa"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:90d558489962fd4918143277a773316e56c72da56ec7aa3dc3dbbe20fdfed15b"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ac7ffc7ad6d040517be39eb591cac5ff87416c2537df6ba3cba3bae290c0fed"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:7ed9e526742851e8d5cc9e6cf41427dfc6068d4f5a3bb03659444b4cabf6bc26"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:8bdb58ff7ba23002a4c5808d608e4e6c687175724f54a5dade5fa8c67b604e4d"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:6b3251890fff30ee142c44144871185dbe13b11bab478a88887a639655be1068"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:b4a23f61ce87adf89be746c8a8974fe1c823c891d8f86eb218bb957c924bb143"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:efcb3f6676480691518c177e3b465bcddf57cea040302f9f4e6e191af91174d4"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-win32.whl", hash = "sha256:d965bba47ddeec8cd560687584e88cf699fd28f192ceb452d1d7ee807c5597b7"}, + {file = "charset_normalizer-3.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:96b02a3dc4381e5494fad39be677abcb5e6634bf7b4fa83a6dd3112607547001"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:95f2a5796329323b8f0512e09dbb7a1860c46a39da62ecb2324f116fa8fdc85c"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c002b4ffc0be611f0d9da932eb0f704fe2602a9a949d1f738e4c34c75b0863d5"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a981a536974bbc7a512cf44ed14938cf01030a99e9b3a06dd59578882f06f985"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3287761bc4ee9e33561a7e058c72ac0938c4f57fe49a09eae428fd88aafe7bb6"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42cb296636fcc8b0644486d15c12376cb9fa75443e00fb25de0b8602e64c1714"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0a55554a2fa0d408816b3b5cedf0045f4b8e1a6065aec45849de2d6f3f8e9786"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:c083af607d2515612056a31f0a8d9e0fcb5876b7bfc0abad3ecd275bc4ebc2d5"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:87d1351268731db79e0f8e745d92493ee2841c974128ef629dc518b937d9194c"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:bd8f7df7d12c2db9fab40bdd87a7c09b1530128315d047a086fa3ae3435cb3a8"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:c180f51afb394e165eafe4ac2936a14bee3eb10debc9d9e4db8958fe36afe711"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:8c622a5fe39a48f78944a87d4fb8a53ee07344641b0562c540d840748571b811"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-win32.whl", hash = "sha256:db364eca23f876da6f9e16c9da0df51aa4f104a972735574842618b8c6d999d4"}, + {file = "charset_normalizer-3.3.2-cp37-cp37m-win_amd64.whl", hash = "sha256:86216b5cee4b06df986d214f664305142d9c76df9b6512be2738aa72a2048f99"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:6463effa3186ea09411d50efc7d85360b38d5f09b870c48e4600f63af490e56a"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6c4caeef8fa63d06bd437cd4bdcf3ffefe6738fb1b25951440d80dc7df8c03ac"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:37e55c8e51c236f95b033f6fb391d7d7970ba5fe7ff453dad675e88cf303377a"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fb69256e180cb6c8a894fee62b3afebae785babc1ee98b81cdf68bbca1987f33"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ae5f4161f18c61806f411a13b0310bea87f987c7d2ecdbdaad0e94eb2e404238"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b2b0a0c0517616b6869869f8c581d4eb2dd83a4d79e0ebcb7d373ef9956aeb0a"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:45485e01ff4d3630ec0d9617310448a8702f70e9c01906b0d0118bdf9d124cf2"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eb00ed941194665c332bf8e078baf037d6c35d7c4f3102ea2d4f16ca94a26dc8"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:2127566c664442652f024c837091890cb1942c30937add288223dc895793f898"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:a50aebfa173e157099939b17f18600f72f84eed3049e743b68ad15bd69b6bf99"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:4d0d1650369165a14e14e1e47b372cfcb31d6ab44e6e33cb2d4e57265290044d"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:923c0c831b7cfcb071580d3f46c4baf50f174be571576556269530f4bbd79d04"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:06a81e93cd441c56a9b65d8e1d043daeb97a3d0856d177d5c90ba85acb3db087"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-win32.whl", hash = "sha256:6ef1d82a3af9d3eecdba2321dc1b3c238245d890843e040e41e470ffa64c3e25"}, + {file = "charset_normalizer-3.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:eb8821e09e916165e160797a6c17edda0679379a4be5c716c260e836e122f54b"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c235ebd9baae02f1b77bcea61bce332cb4331dc3617d254df3323aa01ab47bd4"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:5b4c145409bef602a690e7cfad0a15a55c13320ff7a3ad7ca59c13bb8ba4d45d"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:68d1f8a9e9e37c1223b656399be5d6b448dea850bed7d0f87a8311f1ff3dabb0"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22afcb9f253dac0696b5a4be4a1c0f8762f8239e21b99680099abd9b2b1b2269"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e27ad930a842b4c5eb8ac0016b0a54f5aebbe679340c26101df33424142c143c"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1f79682fbe303db92bc2b1136016a38a42e835d932bab5b3b1bfcfbf0640e519"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b261ccdec7821281dade748d088bb6e9b69e6d15b30652b74cbbac25e280b796"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:122c7fa62b130ed55f8f285bfd56d5f4b4a5b503609d181f9ad85e55c89f4185"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:d0eccceffcb53201b5bfebb52600a5fb483a20b61da9dbc885f8b103cbe7598c"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9f96df6923e21816da7e0ad3fd47dd8f94b2a5ce594e00677c0013018b813458"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:7f04c839ed0b6b98b1a7501a002144b76c18fb1c1850c8b98d458ac269e26ed2"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:34d1c8da1e78d2e001f363791c98a272bb734000fcef47a491c1e3b0505657a8"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ff8fa367d09b717b2a17a052544193ad76cd49979c805768879cb63d9ca50561"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-win32.whl", hash = "sha256:aed38f6e4fb3f5d6bf81bfa990a07806be9d83cf7bacef998ab1a9bd660a581f"}, + {file = "charset_normalizer-3.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:b01b88d45a6fcb69667cd6d2f7a9aeb4bf53760d7fc536bf679ec94fe9f3ff3d"}, + {file = "charset_normalizer-3.3.2-py3-none-any.whl", hash = "sha256:3e4d1f6587322d2788836a99c69062fbb091331ec940e02d12d179c1d53e25fc"}, ] [[package]] @@ -141,63 +141,63 @@ files = [ [[package]] name = "coverage" -version = "7.3.1" +version = "7.3.2" description = "Code coverage measurement for Python" optional = false python-versions = ">=3.8" files = [ - {file = "coverage-7.3.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:cd0f7429ecfd1ff597389907045ff209c8fdb5b013d38cfa7c60728cb484b6e3"}, - {file = "coverage-7.3.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:966f10df9b2b2115da87f50f6a248e313c72a668248be1b9060ce935c871f276"}, - {file = "coverage-7.3.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0575c37e207bb9b98b6cf72fdaaa18ac909fb3d153083400c2d48e2e6d28bd8e"}, - {file = "coverage-7.3.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:245c5a99254e83875c7fed8b8b2536f040997a9b76ac4c1da5bff398c06e860f"}, - {file = "coverage-7.3.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c96dd7798d83b960afc6c1feb9e5af537fc4908852ef025600374ff1a017392"}, - {file = "coverage-7.3.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:de30c1aa80f30af0f6b2058a91505ea6e36d6535d437520067f525f7df123887"}, - {file = "coverage-7.3.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:50dd1e2dd13dbbd856ffef69196781edff26c800a74f070d3b3e3389cab2600d"}, - {file = "coverage-7.3.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b9c0c19f70d30219113b18fe07e372b244fb2a773d4afde29d5a2f7930765136"}, - {file = "coverage-7.3.1-cp310-cp310-win32.whl", hash = "sha256:770f143980cc16eb601ccfd571846e89a5fe4c03b4193f2e485268f224ab602f"}, - {file = "coverage-7.3.1-cp310-cp310-win_amd64.whl", hash = "sha256:cdd088c00c39a27cfa5329349cc763a48761fdc785879220d54eb785c8a38520"}, - {file = "coverage-7.3.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:74bb470399dc1989b535cb41f5ca7ab2af561e40def22d7e188e0a445e7639e3"}, - {file = "coverage-7.3.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:025ded371f1ca280c035d91b43252adbb04d2aea4c7105252d3cbc227f03b375"}, - {file = "coverage-7.3.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6191b3a6ad3e09b6cfd75b45c6aeeffe7e3b0ad46b268345d159b8df8d835f9"}, - {file = "coverage-7.3.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7eb0b188f30e41ddd659a529e385470aa6782f3b412f860ce22b2491c89b8593"}, - {file = "coverage-7.3.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:75c8f0df9dfd8ff745bccff75867d63ef336e57cc22b2908ee725cc552689ec8"}, - {file = "coverage-7.3.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:7eb3cd48d54b9bd0e73026dedce44773214064be93611deab0b6a43158c3d5a0"}, - {file = "coverage-7.3.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:ac3c5b7e75acac31e490b7851595212ed951889918d398b7afa12736c85e13ce"}, - {file = "coverage-7.3.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5b4ee7080878077af0afa7238df1b967f00dc10763f6e1b66f5cced4abebb0a3"}, - {file = "coverage-7.3.1-cp311-cp311-win32.whl", hash = "sha256:229c0dd2ccf956bf5aeede7e3131ca48b65beacde2029f0361b54bf93d36f45a"}, - {file = "coverage-7.3.1-cp311-cp311-win_amd64.whl", hash = "sha256:c6f55d38818ca9596dc9019eae19a47410d5322408140d9a0076001a3dcb938c"}, - {file = "coverage-7.3.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5289490dd1c3bb86de4730a92261ae66ea8d44b79ed3cc26464f4c2cde581fbc"}, - {file = "coverage-7.3.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ca833941ec701fda15414be400c3259479bfde7ae6d806b69e63b3dc423b1832"}, - {file = "coverage-7.3.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cd694e19c031733e446c8024dedd12a00cda87e1c10bd7b8539a87963685e969"}, - {file = "coverage-7.3.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aab8e9464c00da5cb9c536150b7fbcd8850d376d1151741dd0d16dfe1ba4fd26"}, - {file = "coverage-7.3.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:87d38444efffd5b056fcc026c1e8d862191881143c3aa80bb11fcf9dca9ae204"}, - {file = "coverage-7.3.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:8a07b692129b8a14ad7a37941a3029c291254feb7a4237f245cfae2de78de037"}, - {file = "coverage-7.3.1-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:2829c65c8faaf55b868ed7af3c7477b76b1c6ebeee99a28f59a2cb5907a45760"}, - {file = "coverage-7.3.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:1f111a7d85658ea52ffad7084088277135ec5f368457275fc57f11cebb15607f"}, - {file = "coverage-7.3.1-cp312-cp312-win32.whl", hash = "sha256:c397c70cd20f6df7d2a52283857af622d5f23300c4ca8e5bd8c7a543825baa5a"}, - {file = "coverage-7.3.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ae4c6da8b3d123500f9525b50bf0168023313963e0e2e814badf9000dd6ef92"}, - {file = "coverage-7.3.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:ca70466ca3a17460e8fc9cea7123c8cbef5ada4be3140a1ef8f7b63f2f37108f"}, - {file = "coverage-7.3.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:f2781fd3cabc28278dc982a352f50c81c09a1a500cc2086dc4249853ea96b981"}, - {file = "coverage-7.3.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6407424621f40205bbe6325686417e5e552f6b2dba3535dd1f90afc88a61d465"}, - {file = "coverage-7.3.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:04312b036580ec505f2b77cbbdfb15137d5efdfade09156961f5277149f5e344"}, - {file = "coverage-7.3.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ac9ad38204887349853d7c313f53a7b1c210ce138c73859e925bc4e5d8fc18e7"}, - {file = "coverage-7.3.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:53669b79f3d599da95a0afbef039ac0fadbb236532feb042c534fbb81b1a4e40"}, - {file = "coverage-7.3.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:614f1f98b84eb256e4f35e726bfe5ca82349f8dfa576faabf8a49ca09e630086"}, - {file = "coverage-7.3.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:f1a317fdf5c122ad642db8a97964733ab7c3cf6009e1a8ae8821089993f175ff"}, - {file = "coverage-7.3.1-cp38-cp38-win32.whl", hash = "sha256:defbbb51121189722420a208957e26e49809feafca6afeef325df66c39c4fdb3"}, - {file = "coverage-7.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:f4f456590eefb6e1b3c9ea6328c1e9fa0f1006e7481179d749b3376fc793478e"}, - {file = "coverage-7.3.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:f12d8b11a54f32688b165fd1a788c408f927b0960984b899be7e4c190ae758f1"}, - {file = "coverage-7.3.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f09195dda68d94a53123883de75bb97b0e35f5f6f9f3aa5bf6e496da718f0cb6"}, - {file = "coverage-7.3.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c6601a60318f9c3945be6ea0f2a80571f4299b6801716f8a6e4846892737ebe4"}, - {file = "coverage-7.3.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:07d156269718670d00a3b06db2288b48527fc5f36859425ff7cec07c6b367745"}, - {file = "coverage-7.3.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:636a8ac0b044cfeccae76a36f3b18264edcc810a76a49884b96dd744613ec0b7"}, - {file = "coverage-7.3.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5d991e13ad2ed3aced177f524e4d670f304c8233edad3210e02c465351f785a0"}, - {file = "coverage-7.3.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:586649ada7cf139445da386ab6f8ef00e6172f11a939fc3b2b7e7c9082052fa0"}, - {file = "coverage-7.3.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:4aba512a15a3e1e4fdbfed2f5392ec221434a614cc68100ca99dcad7af29f3f8"}, - {file = "coverage-7.3.1-cp39-cp39-win32.whl", hash = "sha256:6bc6f3f4692d806831c136c5acad5ccedd0262aa44c087c46b7101c77e139140"}, - {file = "coverage-7.3.1-cp39-cp39-win_amd64.whl", hash = "sha256:553d7094cb27db58ea91332e8b5681bac107e7242c23f7629ab1316ee73c4981"}, - {file = "coverage-7.3.1-pp38.pp39.pp310-none-any.whl", hash = "sha256:220eb51f5fb38dfdb7e5d54284ca4d0cd70ddac047d750111a68ab1798945194"}, - {file = "coverage-7.3.1.tar.gz", hash = "sha256:6cb7fe1581deb67b782c153136541e20901aa312ceedaf1467dcb35255787952"}, + {file = "coverage-7.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d872145f3a3231a5f20fd48500274d7df222e291d90baa2026cc5152b7ce86bf"}, + {file = "coverage-7.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:310b3bb9c91ea66d59c53fa4989f57d2436e08f18fb2f421a1b0b6b8cc7fffda"}, + {file = "coverage-7.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f47d39359e2c3779c5331fc740cf4bce6d9d680a7b4b4ead97056a0ae07cb49a"}, + {file = "coverage-7.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aa72dbaf2c2068404b9870d93436e6d23addd8bbe9295f49cbca83f6e278179c"}, + {file = "coverage-7.3.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:beaa5c1b4777f03fc63dfd2a6bd820f73f036bfb10e925fce067b00a340d0f3f"}, + {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:dbc1b46b92186cc8074fee9d9fbb97a9dd06c6cbbef391c2f59d80eabdf0faa6"}, + {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:315a989e861031334d7bee1f9113c8770472db2ac484e5b8c3173428360a9148"}, + {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:d1bc430677773397f64a5c88cb522ea43175ff16f8bfcc89d467d974cb2274f9"}, + {file = "coverage-7.3.2-cp310-cp310-win32.whl", hash = "sha256:a889ae02f43aa45032afe364c8ae84ad3c54828c2faa44f3bfcafecb5c96b02f"}, + {file = "coverage-7.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:c0ba320de3fb8c6ec16e0be17ee1d3d69adcda99406c43c0409cb5c41788a611"}, + {file = "coverage-7.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ac8c802fa29843a72d32ec56d0ca792ad15a302b28ca6203389afe21f8fa062c"}, + {file = "coverage-7.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:89a937174104339e3a3ffcf9f446c00e3a806c28b1841c63edb2b369310fd074"}, + {file = "coverage-7.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e267e9e2b574a176ddb983399dec325a80dbe161f1a32715c780b5d14b5f583a"}, + {file = "coverage-7.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2443cbda35df0d35dcfb9bf8f3c02c57c1d6111169e3c85fc1fcc05e0c9f39a3"}, + {file = "coverage-7.3.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4175e10cc8dda0265653e8714b3174430b07c1dca8957f4966cbd6c2b1b8065a"}, + {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0cbf38419fb1a347aaf63481c00f0bdc86889d9fbf3f25109cf96c26b403fda1"}, + {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:5c913b556a116b8d5f6ef834038ba983834d887d82187c8f73dec21049abd65c"}, + {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1981f785239e4e39e6444c63a98da3a1db8e971cb9ceb50a945ba6296b43f312"}, + {file = "coverage-7.3.2-cp311-cp311-win32.whl", hash = "sha256:43668cabd5ca8258f5954f27a3aaf78757e6acf13c17604d89648ecc0cc66640"}, + {file = "coverage-7.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10c39c0452bf6e694511c901426d6b5ac005acc0f78ff265dbe36bf81f808a2"}, + {file = "coverage-7.3.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:4cbae1051ab791debecc4a5dcc4a1ff45fc27b91b9aee165c8a27514dd160836"}, + {file = "coverage-7.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:12d15ab5833a997716d76f2ac1e4b4d536814fc213c85ca72756c19e5a6b3d63"}, + {file = "coverage-7.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c7bba973ebee5e56fe9251300c00f1579652587a9f4a5ed8404b15a0471f216"}, + {file = "coverage-7.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fe494faa90ce6381770746077243231e0b83ff3f17069d748f645617cefe19d4"}, + {file = "coverage-7.3.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6e9589bd04d0461a417562649522575d8752904d35c12907d8c9dfeba588faf"}, + {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d51ac2a26f71da1b57f2dc81d0e108b6ab177e7d30e774db90675467c847bbdf"}, + {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:99b89d9f76070237975b315b3d5f4d6956ae354a4c92ac2388a5695516e47c84"}, + {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:fa28e909776dc69efb6ed975a63691bc8172b64ff357e663a1bb06ff3c9b589a"}, + {file = "coverage-7.3.2-cp312-cp312-win32.whl", hash = "sha256:289fe43bf45a575e3ab10b26d7b6f2ddb9ee2dba447499f5401cfb5ecb8196bb"}, + {file = "coverage-7.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:7dbc3ed60e8659bc59b6b304b43ff9c3ed858da2839c78b804973f613d3e92ed"}, + {file = "coverage-7.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f94b734214ea6a36fe16e96a70d941af80ff3bfd716c141300d95ebc85339738"}, + {file = "coverage-7.3.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:af3d828d2c1cbae52d34bdbb22fcd94d1ce715d95f1a012354a75e5913f1bda2"}, + {file = "coverage-7.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:630b13e3036e13c7adc480ca42fa7afc2a5d938081d28e20903cf7fd687872e2"}, + {file = "coverage-7.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c9eacf273e885b02a0273bb3a2170f30e2d53a6d53b72dbe02d6701b5296101c"}, + {file = "coverage-7.3.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d8f17966e861ff97305e0801134e69db33b143bbfb36436efb9cfff6ec7b2fd9"}, + {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:b4275802d16882cf9c8b3d057a0839acb07ee9379fa2749eca54efbce1535b82"}, + {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:72c0cfa5250f483181e677ebc97133ea1ab3eb68645e494775deb6a7f6f83901"}, + {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:cb536f0dcd14149425996821a168f6e269d7dcd2c273a8bff8201e79f5104e76"}, + {file = "coverage-7.3.2-cp38-cp38-win32.whl", hash = "sha256:307adb8bd3abe389a471e649038a71b4eb13bfd6b7dd9a129fa856f5c695cf92"}, + {file = "coverage-7.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:88ed2c30a49ea81ea3b7f172e0269c182a44c236eb394718f976239892c0a27a"}, + {file = "coverage-7.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b631c92dfe601adf8f5ebc7fc13ced6bb6e9609b19d9a8cd59fa47c4186ad1ce"}, + {file = "coverage-7.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:d3d9df4051c4a7d13036524b66ecf7a7537d14c18a384043f30a303b146164e9"}, + {file = "coverage-7.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f7363d3b6a1119ef05015959ca24a9afc0ea8a02c687fe7e2d557705375c01f"}, + {file = "coverage-7.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2f11cc3c967a09d3695d2a6f03fb3e6236622b93be7a4b5dc09166a861be6d25"}, + {file = "coverage-7.3.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:149de1d2401ae4655c436a3dced6dd153f4c3309f599c3d4bd97ab172eaf02d9"}, + {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:3a4006916aa6fee7cd38db3bfc95aa9c54ebb4ffbfc47c677c8bba949ceba0a6"}, + {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9028a3871280110d6e1aa2df1afd5ef003bab5fb1ef421d6dc748ae1c8ef2ebc"}, + {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9f805d62aec8eb92bab5b61c0f07329275b6f41c97d80e847b03eb894f38d083"}, + {file = "coverage-7.3.2-cp39-cp39-win32.whl", hash = "sha256:d1c88ec1a7ff4ebca0219f5b1ef863451d828cccf889c173e1253aa84b1e07ce"}, + {file = "coverage-7.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:b4767da59464bb593c07afceaddea61b154136300881844768037fd5e859353f"}, + {file = "coverage-7.3.2-pp38.pp39.pp310-none-any.whl", hash = "sha256:ae97af89f0fbf373400970c0a21eef5aa941ffeed90aee43650b81f7d7f47637"}, + {file = "coverage-7.3.2.tar.gz", hash = "sha256:be32ad29341b0170e795ca590e1c07e81fc061cb5b10c74ce7203491484404ef"}, ] [package.extras] @@ -219,13 +219,13 @@ test = ["pytest (>=6)"] [[package]] name = "googleapis-common-protos" -version = "1.60.0" +version = "1.61.0" description = "Common protobufs used in Google APIs" optional = true python-versions = ">=3.7" files = [ - {file = "googleapis-common-protos-1.60.0.tar.gz", hash = "sha256:e73ebb404098db405ba95d1e1ae0aa91c3e15a71da031a2eeb6b2e23e7bc3708"}, - {file = "googleapis_common_protos-1.60.0-py2.py3-none-any.whl", hash = "sha256:69f9bbcc6acde92cab2db95ce30a70bd2b81d20b12eff3f1aabaffcbe8a93918"}, + {file = "googleapis-common-protos-1.61.0.tar.gz", hash = "sha256:8a64866a97f6304a7179873a465d6eee97b7a24ec6cfd78e0f575e96b821240b"}, + {file = "googleapis_common_protos-1.61.0-py2.py3-none-any.whl", hash = "sha256:22f1915393bb3245343f6efe87f6fe868532efc12aa26b391b15132e1279f1c0"}, ] [package.dependencies] @@ -248,71 +248,85 @@ files = [ [package.dependencies] googleapis-common-protos = "*" +[[package]] +name = "grpc-stubs" +version = "1.53.0.3" +description = "Mypy stubs for gRPC" +optional = false +python-versions = ">=3.6" +files = [ + {file = "grpc-stubs-1.53.0.3.tar.gz", hash = "sha256:6e5d75cdc88c0ba918e2f8395851f1e6a7c19a7c7fc3e902bde4601c7a1cbf96"}, + {file = "grpc_stubs-1.53.0.3-py3-none-any.whl", hash = "sha256:312c3c697089344936c9779118a105bcc4ccc8eef053265f3f23086acdba2683"}, +] + +[package.dependencies] +grpcio = "*" + [[package]] name = "grpcio" -version = "1.59.0" +version = "1.59.2" description = "HTTP/2-based RPC framework" -optional = true +optional = false python-versions = ">=3.7" files = [ - {file = "grpcio-1.59.0-cp310-cp310-linux_armv7l.whl", hash = "sha256:225e5fa61c35eeaebb4e7491cd2d768cd8eb6ed00f2664fa83a58f29418b39fd"}, - {file = "grpcio-1.59.0-cp310-cp310-macosx_12_0_universal2.whl", hash = "sha256:b95ec8ecc4f703f5caaa8d96e93e40c7f589bad299a2617bdb8becbcce525539"}, - {file = "grpcio-1.59.0-cp310-cp310-manylinux_2_17_aarch64.whl", hash = "sha256:1a839ba86764cc48226f50b924216000c79779c563a301586a107bda9cbe9dcf"}, - {file = "grpcio-1.59.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f6cfe44a5d7c7d5f1017a7da1c8160304091ca5dc64a0f85bca0d63008c3137a"}, - {file = "grpcio-1.59.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0fcf53df684fcc0154b1e61f6b4a8c4cf5f49d98a63511e3f30966feff39cd0"}, - {file = "grpcio-1.59.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:fa66cac32861500f280bb60fe7d5b3e22d68c51e18e65367e38f8669b78cea3b"}, - {file = "grpcio-1.59.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8cd2d38c2d52f607d75a74143113174c36d8a416d9472415eab834f837580cf7"}, - {file = "grpcio-1.59.0-cp310-cp310-win32.whl", hash = "sha256:228b91ce454876d7eed74041aff24a8f04c0306b7250a2da99d35dd25e2a1211"}, - {file = "grpcio-1.59.0-cp310-cp310-win_amd64.whl", hash = "sha256:ca87ee6183421b7cea3544190061f6c1c3dfc959e0b57a5286b108511fd34ff4"}, - {file = "grpcio-1.59.0-cp311-cp311-linux_armv7l.whl", hash = "sha256:c173a87d622ea074ce79be33b952f0b424fa92182063c3bda8625c11d3585d09"}, - {file = "grpcio-1.59.0-cp311-cp311-macosx_10_10_universal2.whl", hash = "sha256:ec78aebb9b6771d6a1de7b6ca2f779a2f6113b9108d486e904bde323d51f5589"}, - {file = "grpcio-1.59.0-cp311-cp311-manylinux_2_17_aarch64.whl", hash = "sha256:0b84445fa94d59e6806c10266b977f92fa997db3585f125d6b751af02ff8b9fe"}, - {file = "grpcio-1.59.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c251d22de8f9f5cca9ee47e4bade7c5c853e6e40743f47f5cc02288ee7a87252"}, - {file = "grpcio-1.59.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:956f0b7cb465a65de1bd90d5a7475b4dc55089b25042fe0f6c870707e9aabb1d"}, - {file = "grpcio-1.59.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:38da5310ef84e16d638ad89550b5b9424df508fd5c7b968b90eb9629ca9be4b9"}, - {file = "grpcio-1.59.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:63982150a7d598281fa1d7ffead6096e543ff8be189d3235dd2b5604f2c553e5"}, - {file = "grpcio-1.59.0-cp311-cp311-win32.whl", hash = "sha256:50eff97397e29eeee5df106ea1afce3ee134d567aa2c8e04fabab05c79d791a7"}, - {file = "grpcio-1.59.0-cp311-cp311-win_amd64.whl", hash = "sha256:15f03bd714f987d48ae57fe092cf81960ae36da4e520e729392a59a75cda4f29"}, - {file = "grpcio-1.59.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:f1feb034321ae2f718172d86b8276c03599846dc7bb1792ae370af02718f91c5"}, - {file = "grpcio-1.59.0-cp312-cp312-macosx_10_10_universal2.whl", hash = "sha256:d09bd2a4e9f5a44d36bb8684f284835c14d30c22d8ec92ce796655af12163588"}, - {file = "grpcio-1.59.0-cp312-cp312-manylinux_2_17_aarch64.whl", hash = "sha256:2f120d27051e4c59db2f267b71b833796770d3ea36ca712befa8c5fff5da6ebd"}, - {file = "grpcio-1.59.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba0ca727a173ee093f49ead932c051af463258b4b493b956a2c099696f38aa66"}, - {file = "grpcio-1.59.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5711c51e204dc52065f4a3327dca46e69636a0b76d3e98c2c28c4ccef9b04c52"}, - {file = "grpcio-1.59.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:d74f7d2d7c242a6af9d4d069552ec3669965b74fed6b92946e0e13b4168374f9"}, - {file = "grpcio-1.59.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3859917de234a0a2a52132489c4425a73669de9c458b01c9a83687f1f31b5b10"}, - {file = "grpcio-1.59.0-cp312-cp312-win32.whl", hash = "sha256:de2599985b7c1b4ce7526e15c969d66b93687571aa008ca749d6235d056b7205"}, - {file = "grpcio-1.59.0-cp312-cp312-win_amd64.whl", hash = "sha256:598f3530231cf10ae03f4ab92d48c3be1fee0c52213a1d5958df1a90957e6a88"}, - {file = "grpcio-1.59.0-cp37-cp37m-linux_armv7l.whl", hash = "sha256:b34c7a4c31841a2ea27246a05eed8a80c319bfc0d3e644412ec9ce437105ff6c"}, - {file = "grpcio-1.59.0-cp37-cp37m-macosx_10_10_universal2.whl", hash = "sha256:c4dfdb49f4997dc664f30116af2d34751b91aa031f8c8ee251ce4dcfc11277b0"}, - {file = "grpcio-1.59.0-cp37-cp37m-manylinux_2_17_aarch64.whl", hash = "sha256:61bc72a00ecc2b79d9695220b4d02e8ba53b702b42411397e831c9b0589f08a3"}, - {file = "grpcio-1.59.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f367e4b524cb319e50acbdea57bb63c3b717c5d561974ace0b065a648bb3bad3"}, - {file = "grpcio-1.59.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:849c47ef42424c86af069a9c5e691a765e304079755d5c29eff511263fad9c2a"}, - {file = "grpcio-1.59.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:c0488c2b0528e6072010182075615620071371701733c63ab5be49140ed8f7f0"}, - {file = "grpcio-1.59.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:611d9aa0017fa386809bddcb76653a5ab18c264faf4d9ff35cb904d44745f575"}, - {file = "grpcio-1.59.0-cp37-cp37m-win_amd64.whl", hash = "sha256:e5378785dce2b91eb2e5b857ec7602305a3b5cf78311767146464bfa365fc897"}, - {file = "grpcio-1.59.0-cp38-cp38-linux_armv7l.whl", hash = "sha256:fe976910de34d21057bcb53b2c5e667843588b48bf11339da2a75f5c4c5b4055"}, - {file = "grpcio-1.59.0-cp38-cp38-macosx_10_10_universal2.whl", hash = "sha256:c041a91712bf23b2a910f61e16565a05869e505dc5a5c025d429ca6de5de842c"}, - {file = "grpcio-1.59.0-cp38-cp38-manylinux_2_17_aarch64.whl", hash = "sha256:0ae444221b2c16d8211b55326f8ba173ba8f8c76349bfc1768198ba592b58f74"}, - {file = "grpcio-1.59.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ceb1e68135788c3fce2211de86a7597591f0b9a0d2bb80e8401fd1d915991bac"}, - {file = "grpcio-1.59.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c4b1cc3a9dc1924d2eb26eec8792fedd4b3fcd10111e26c1d551f2e4eda79ce"}, - {file = "grpcio-1.59.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:871371ce0c0055d3db2a86fdebd1e1d647cf21a8912acc30052660297a5a6901"}, - {file = "grpcio-1.59.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:93e9cb546e610829e462147ce724a9cb108e61647a3454500438a6deef610be1"}, - {file = "grpcio-1.59.0-cp38-cp38-win32.whl", hash = "sha256:f21917aa50b40842b51aff2de6ebf9e2f6af3fe0971c31960ad6a3a2b24988f4"}, - {file = "grpcio-1.59.0-cp38-cp38-win_amd64.whl", hash = "sha256:14890da86a0c0e9dc1ea8e90101d7a3e0e7b1e71f4487fab36e2bfd2ecadd13c"}, - {file = "grpcio-1.59.0-cp39-cp39-linux_armv7l.whl", hash = "sha256:34341d9e81a4b669a5f5dca3b2a760b6798e95cdda2b173e65d29d0b16692857"}, - {file = "grpcio-1.59.0-cp39-cp39-macosx_10_10_universal2.whl", hash = "sha256:986de4aa75646e963466b386a8c5055c8b23a26a36a6c99052385d6fe8aaf180"}, - {file = "grpcio-1.59.0-cp39-cp39-manylinux_2_17_aarch64.whl", hash = "sha256:aca8a24fef80bef73f83eb8153f5f5a0134d9539b4c436a716256b311dda90a6"}, - {file = "grpcio-1.59.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:936b2e04663660c600d5173bc2cc84e15adbad9c8f71946eb833b0afc205b996"}, - {file = "grpcio-1.59.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc8bf2e7bc725e76c0c11e474634a08c8f24bcf7426c0c6d60c8f9c6e70e4d4a"}, - {file = "grpcio-1.59.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:81d86a096ccd24a57fa5772a544c9e566218bc4de49e8c909882dae9d73392df"}, - {file = "grpcio-1.59.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:2ea95cd6abbe20138b8df965b4a8674ec312aaef3147c0f46a0bac661f09e8d0"}, - {file = "grpcio-1.59.0-cp39-cp39-win32.whl", hash = "sha256:3b8ff795d35a93d1df6531f31c1502673d1cebeeba93d0f9bd74617381507e3f"}, - {file = "grpcio-1.59.0-cp39-cp39-win_amd64.whl", hash = "sha256:38823bd088c69f59966f594d087d3a929d1ef310506bee9e3648317660d65b81"}, - {file = "grpcio-1.59.0.tar.gz", hash = "sha256:acf70a63cf09dd494000007b798aff88a436e1c03b394995ce450be437b8e54f"}, + {file = "grpcio-1.59.2-cp310-cp310-linux_armv7l.whl", hash = "sha256:d2fa68a96a30dd240be80bbad838a0ac81a61770611ff7952b889485970c4c71"}, + {file = "grpcio-1.59.2-cp310-cp310-macosx_12_0_universal2.whl", hash = "sha256:cf0dead5a2c5a3347af2cfec7131d4f2a2e03c934af28989c9078f8241a491fa"}, + {file = "grpcio-1.59.2-cp310-cp310-manylinux_2_17_aarch64.whl", hash = "sha256:e420ced29b5904cdf9ee5545e23f9406189d8acb6750916c2db4793dada065c6"}, + {file = "grpcio-1.59.2-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2b230028a008ae1d0f430acb227d323ff8a619017415cf334c38b457f814119f"}, + {file = "grpcio-1.59.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0a4a3833c0e067f3558538727235cd8a49709bff1003200bbdefa2f09334e4b1"}, + {file = "grpcio-1.59.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6b25ed37c27e652db01be341af93fbcea03d296c024d8a0e680017a268eb85dd"}, + {file = "grpcio-1.59.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:73abb8584b0cf74d37f5ef61c10722adc7275502ab71789a8fe3cb7ef04cf6e2"}, + {file = "grpcio-1.59.2-cp310-cp310-win32.whl", hash = "sha256:d6f70406695e3220f09cd7a2f879333279d91aa4a8a1d34303b56d61a8180137"}, + {file = "grpcio-1.59.2-cp310-cp310-win_amd64.whl", hash = "sha256:3c61d641d4f409c5ae46bfdd89ea42ce5ea233dcf69e74ce9ba32b503c727e29"}, + {file = "grpcio-1.59.2-cp311-cp311-linux_armv7l.whl", hash = "sha256:3059668df17627f0e0fa680e9ef8c995c946c792612e9518f5cc1503be14e90b"}, + {file = "grpcio-1.59.2-cp311-cp311-macosx_10_10_universal2.whl", hash = "sha256:72ca2399097c0b758198f2ff30f7178d680de8a5cfcf3d9b73a63cf87455532e"}, + {file = "grpcio-1.59.2-cp311-cp311-manylinux_2_17_aarch64.whl", hash = "sha256:c978f864b35f2261e0819f5cd88b9830b04dc51bcf055aac3c601e525a10d2ba"}, + {file = "grpcio-1.59.2-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9411e24328a2302e279e70cae6e479f1fddde79629fcb14e03e6d94b3956eabf"}, + {file = "grpcio-1.59.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb7e0fe6ad73b7f06d7e2b689c19a71cf5cc48f0c2bf8608469e51ffe0bd2867"}, + {file = "grpcio-1.59.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c2504eed520958a5b77cc99458297cb7906308cb92327f35fb7fbbad4e9b2188"}, + {file = "grpcio-1.59.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:2171c39f355ba5b551c5d5928d65aa6c69807fae195b86ef4a7d125bcdb860a9"}, + {file = "grpcio-1.59.2-cp311-cp311-win32.whl", hash = "sha256:d2794f0e68b3085d99b4f6ff9c089f6fdd02b32b9d3efdfbb55beac1bf22d516"}, + {file = "grpcio-1.59.2-cp311-cp311-win_amd64.whl", hash = "sha256:2067274c88bc6de89c278a672a652b4247d088811ece781a4858b09bdf8448e3"}, + {file = "grpcio-1.59.2-cp312-cp312-linux_armv7l.whl", hash = "sha256:535561990e075fa6bd4b16c4c3c1096b9581b7bb35d96fac4650f1181e428268"}, + {file = "grpcio-1.59.2-cp312-cp312-macosx_10_10_universal2.whl", hash = "sha256:a213acfbf186b9f35803b52e4ca9addb153fc0b67f82a48f961be7000ecf6721"}, + {file = "grpcio-1.59.2-cp312-cp312-manylinux_2_17_aarch64.whl", hash = "sha256:6959fb07e8351e20501ffb8cc4074c39a0b7ef123e1c850a7f8f3afdc3a3da01"}, + {file = "grpcio-1.59.2-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e82c5cf1495244adf5252f925ac5932e5fd288b3e5ab6b70bec5593074b7236c"}, + {file = "grpcio-1.59.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:023088764012411affe7db183d1ada3ad9daf2e23ddc719ff46d7061de661340"}, + {file = "grpcio-1.59.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:da2d94c15f88cd40d7e67f7919d4f60110d2b9d5b1e08cf354c2be773ab13479"}, + {file = "grpcio-1.59.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:6009386a2df66159f64ac9f20425ae25229b29b9dd0e1d3dd60043f037e2ad7e"}, + {file = "grpcio-1.59.2-cp312-cp312-win32.whl", hash = "sha256:75c6ecb70e809cf1504465174343113f51f24bc61e22a80ae1c859f3f7034c6d"}, + {file = "grpcio-1.59.2-cp312-cp312-win_amd64.whl", hash = "sha256:cbe946b3e6e60a7b4618f091e62a029cb082b109a9d6b53962dd305087c6e4fd"}, + {file = "grpcio-1.59.2-cp37-cp37m-linux_armv7l.whl", hash = "sha256:f8753a6c88d1d0ba64302309eecf20f70d2770f65ca02d83c2452279085bfcd3"}, + {file = "grpcio-1.59.2-cp37-cp37m-macosx_10_10_universal2.whl", hash = "sha256:f1ef0d39bc1feb420caf549b3c657c871cad4ebbcf0580c4d03816b0590de0cf"}, + {file = "grpcio-1.59.2-cp37-cp37m-manylinux_2_17_aarch64.whl", hash = "sha256:4c93f4abbb54321ee6471e04a00139c80c754eda51064187963ddf98f5cf36a4"}, + {file = "grpcio-1.59.2-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:08d77e682f2bf730a4961eea330e56d2f423c6a9b91ca222e5b1eb24a357b19f"}, + {file = "grpcio-1.59.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ff16d68bf453275466a9a46739061a63584d92f18a0f5b33d19fc97eb69867c"}, + {file = "grpcio-1.59.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4abb717e320e74959517dc8e84a9f48fbe90e9abe19c248541e9418b1ce60acd"}, + {file = "grpcio-1.59.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:36f53c2b3449c015880e7d55a89c992c357f176327b0d2873cdaaf9628a37c69"}, + {file = "grpcio-1.59.2-cp37-cp37m-win_amd64.whl", hash = "sha256:cc3e4cd087f07758b16bef8f31d88dbb1b5da5671d2f03685ab52dece3d7a16e"}, + {file = "grpcio-1.59.2-cp38-cp38-linux_armv7l.whl", hash = "sha256:27f879ae604a7fcf371e59fba6f3ff4635a4c2a64768bd83ff0cac503142fef4"}, + {file = "grpcio-1.59.2-cp38-cp38-macosx_10_10_universal2.whl", hash = "sha256:7cf05053242f61ba94014dd3a986e11a083400a32664058f80bf4cf817c0b3a1"}, + {file = "grpcio-1.59.2-cp38-cp38-manylinux_2_17_aarch64.whl", hash = "sha256:e1727c1c0e394096bb9af185c6923e8ea55a5095b8af44f06903bcc0e06800a2"}, + {file = "grpcio-1.59.2-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5d573e70a6fe77555fb6143c12d3a7d3fa306632a3034b4e7c59ca09721546f8"}, + {file = "grpcio-1.59.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31176aa88f36020055ace9adff2405a33c8bdbfa72a9c4980e25d91b2f196873"}, + {file = "grpcio-1.59.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:11168ef43e4a43ff1b1a65859f3e0ef1a173e277349e7fb16923ff108160a8cd"}, + {file = "grpcio-1.59.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:53c9aa5ddd6857c0a1cd0287225a2a25873a8e09727c2e95c4aebb1be83a766a"}, + {file = "grpcio-1.59.2-cp38-cp38-win32.whl", hash = "sha256:3b4368b33908f683a363f376dfb747d40af3463a6e5044afee07cf9436addf96"}, + {file = "grpcio-1.59.2-cp38-cp38-win_amd64.whl", hash = "sha256:0a754aff9e3af63bdc4c75c234b86b9d14e14a28a30c4e324aed1a9b873d755f"}, + {file = "grpcio-1.59.2-cp39-cp39-linux_armv7l.whl", hash = "sha256:1f9524d1d701e399462d2c90ba7c193e49d1711cf429c0d3d97c966856e03d00"}, + {file = "grpcio-1.59.2-cp39-cp39-macosx_10_10_universal2.whl", hash = "sha256:f93dbf58f03146164048be5426ffde298b237a5e059144847e4940f5b80172c3"}, + {file = "grpcio-1.59.2-cp39-cp39-manylinux_2_17_aarch64.whl", hash = "sha256:6da6dea3a1bacf99b3c2187e296db9a83029ed9c38fd4c52b7c9b7326d13c828"}, + {file = "grpcio-1.59.2-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c5f09cffa619adfb44799fa4a81c2a1ad77c887187613fb0a8f201ab38d89ba1"}, + {file = "grpcio-1.59.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c35aa9657f5d5116d23b934568e0956bd50c615127810fffe3ac356a914c176a"}, + {file = "grpcio-1.59.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:74100fecaec8a535e380cf5f2fb556ff84957d481c13e54051c52e5baac70541"}, + {file = "grpcio-1.59.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:128e20f57c5f27cb0157e73756d1586b83c1b513ebecc83ea0ac37e4b0e4e758"}, + {file = "grpcio-1.59.2-cp39-cp39-win32.whl", hash = "sha256:686e975a5d16602dc0982c7c703948d17184bd1397e16c8ee03511ecb8c4cdda"}, + {file = "grpcio-1.59.2-cp39-cp39-win_amd64.whl", hash = "sha256:242adc47725b9a499ee77c6a2e36688fa6c96484611f33b1be4c57ab075a92dd"}, + {file = "grpcio-1.59.2.tar.gz", hash = "sha256:d8f9cd4ad1be90b0cf350a2f04a38a36e44a026cac1e036ac593dc48efe91d52"}, ] [package.extras] -protobuf = ["grpcio-tools (>=1.59.0)"] +protobuf = ["grpcio-tools (>=1.59.2)"] [[package]] name = "idna" @@ -471,120 +485,197 @@ files = [ {file = "MarkupSafe-2.1.3.tar.gz", hash = "sha256:af598ed32d6ae86f1b747b82783958b1a4ab8f617b06fe68795c7f026abbdcad"}, ] +[[package]] +name = "mypy" +version = "1.6.1" +description = "Optional static typing for Python" +optional = false +python-versions = ">=3.8" +files = [ + {file = "mypy-1.6.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e5012e5cc2ac628177eaac0e83d622b2dd499e28253d4107a08ecc59ede3fc2c"}, + {file = "mypy-1.6.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d8fbb68711905f8912e5af474ca8b78d077447d8f3918997fecbf26943ff3cbb"}, + {file = "mypy-1.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21a1ad938fee7d2d96ca666c77b7c494c3c5bd88dff792220e1afbebb2925b5e"}, + {file = "mypy-1.6.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b96ae2c1279d1065413965c607712006205a9ac541895004a1e0d4f281f2ff9f"}, + {file = "mypy-1.6.1-cp310-cp310-win_amd64.whl", hash = "sha256:40b1844d2e8b232ed92e50a4bd11c48d2daa351f9deee6c194b83bf03e418b0c"}, + {file = "mypy-1.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:81af8adaa5e3099469e7623436881eff6b3b06db5ef75e6f5b6d4871263547e5"}, + {file = "mypy-1.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8c223fa57cb154c7eab5156856c231c3f5eace1e0bed9b32a24696b7ba3c3245"}, + {file = "mypy-1.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8032e00ce71c3ceb93eeba63963b864bf635a18f6c0c12da6c13c450eedb183"}, + {file = "mypy-1.6.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:4c46b51de523817a0045b150ed11b56f9fff55f12b9edd0f3ed35b15a2809de0"}, + {file = "mypy-1.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:19f905bcfd9e167159b3d63ecd8cb5e696151c3e59a1742e79bc3bcb540c42c7"}, + {file = "mypy-1.6.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:82e469518d3e9a321912955cc702d418773a2fd1e91c651280a1bda10622f02f"}, + {file = "mypy-1.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d4473c22cc296425bbbce7e9429588e76e05bc7342da359d6520b6427bf76660"}, + {file = "mypy-1.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59a0d7d24dfb26729e0a068639a6ce3500e31d6655df8557156c51c1cb874ce7"}, + {file = "mypy-1.6.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:cfd13d47b29ed3bbaafaff7d8b21e90d827631afda134836962011acb5904b71"}, + {file = "mypy-1.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:eb4f18589d196a4cbe5290b435d135dee96567e07c2b2d43b5c4621b6501531a"}, + {file = "mypy-1.6.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:41697773aa0bf53ff917aa077e2cde7aa50254f28750f9b88884acea38a16169"}, + {file = "mypy-1.6.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7274b0c57737bd3476d2229c6389b2ec9eefeb090bbaf77777e9d6b1b5a9d143"}, + {file = "mypy-1.6.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbaf4662e498c8c2e352da5f5bca5ab29d378895fa2d980630656178bd607c46"}, + {file = "mypy-1.6.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:bb8ccb4724f7d8601938571bf3f24da0da791fe2db7be3d9e79849cb64e0ae85"}, + {file = "mypy-1.6.1-cp38-cp38-win_amd64.whl", hash = "sha256:68351911e85145f582b5aa6cd9ad666c8958bcae897a1bfda8f4940472463c45"}, + {file = "mypy-1.6.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:49ae115da099dcc0922a7a895c1eec82c1518109ea5c162ed50e3b3594c71208"}, + {file = "mypy-1.6.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8b27958f8c76bed8edaa63da0739d76e4e9ad4ed325c814f9b3851425582a3cd"}, + {file = "mypy-1.6.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:925cd6a3b7b55dfba252b7c4561892311c5358c6b5a601847015a1ad4eb7d332"}, + {file = "mypy-1.6.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8f57e6b6927a49550da3d122f0cb983d400f843a8a82e65b3b380d3d7259468f"}, + {file = "mypy-1.6.1-cp39-cp39-win_amd64.whl", hash = "sha256:a43ef1c8ddfdb9575691720b6352761f3f53d85f1b57d7745701041053deff30"}, + {file = "mypy-1.6.1-py3-none-any.whl", hash = "sha256:4cbe68ef919c28ea561165206a2dcb68591c50f3bcf777932323bc208d949cf1"}, + {file = "mypy-1.6.1.tar.gz", hash = "sha256:4d01c00d09a0be62a4ca3f933e315455bde83f37f892ba4b08ce92f3cf44bcc1"}, +] + +[package.dependencies] +mypy-extensions = ">=1.0.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing-extensions = ">=4.1.0" + +[package.extras] +dmypy = ["psutil (>=4.0)"] +install-types = ["pip"] +reports = ["lxml"] + +[[package]] +name = "mypy-extensions" +version = "1.0.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.5" +files = [ + {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, + {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, +] + [[package]] name = "numpy" -version = "1.24.4" +version = "1.26.1" description = "Fundamental package for array computing in Python" optional = false -python-versions = ">=3.8" +python-versions = "<3.13,>=3.9" files = [ - {file = "numpy-1.24.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c0bfb52d2169d58c1cdb8cc1f16989101639b34c7d3ce60ed70b19c63eba0b64"}, - {file = "numpy-1.24.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ed094d4f0c177b1b8e7aa9cba7d6ceed51c0e569a5318ac0ca9a090680a6a1b1"}, - {file = "numpy-1.24.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79fc682a374c4a8ed08b331bef9c5f582585d1048fa6d80bc6c35bc384eee9b4"}, - {file = "numpy-1.24.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7ffe43c74893dbf38c2b0a1f5428760a1a9c98285553c89e12d70a96a7f3a4d6"}, - {file = "numpy-1.24.4-cp310-cp310-win32.whl", hash = "sha256:4c21decb6ea94057331e111a5bed9a79d335658c27ce2adb580fb4d54f2ad9bc"}, - {file = "numpy-1.24.4-cp310-cp310-win_amd64.whl", hash = "sha256:b4bea75e47d9586d31e892a7401f76e909712a0fd510f58f5337bea9572c571e"}, - {file = "numpy-1.24.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f136bab9c2cfd8da131132c2cf6cc27331dd6fae65f95f69dcd4ae3c3639c810"}, - {file = "numpy-1.24.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e2926dac25b313635e4d6cf4dc4e51c8c0ebfed60b801c799ffc4c32bf3d1254"}, - {file = "numpy-1.24.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:222e40d0e2548690405b0b3c7b21d1169117391c2e82c378467ef9ab4c8f0da7"}, - {file = "numpy-1.24.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7215847ce88a85ce39baf9e89070cb860c98fdddacbaa6c0da3ffb31b3350bd5"}, - {file = "numpy-1.24.4-cp311-cp311-win32.whl", hash = "sha256:4979217d7de511a8d57f4b4b5b2b965f707768440c17cb70fbf254c4b225238d"}, - {file = "numpy-1.24.4-cp311-cp311-win_amd64.whl", hash = "sha256:b7b1fc9864d7d39e28f41d089bfd6353cb5f27ecd9905348c24187a768c79694"}, - {file = "numpy-1.24.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1452241c290f3e2a312c137a9999cdbf63f78864d63c79039bda65ee86943f61"}, - {file = "numpy-1.24.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:04640dab83f7c6c85abf9cd729c5b65f1ebd0ccf9de90b270cd61935eef0197f"}, - {file = "numpy-1.24.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5425b114831d1e77e4b5d812b69d11d962e104095a5b9c3b641a218abcc050e"}, - {file = "numpy-1.24.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd80e219fd4c71fc3699fc1dadac5dcf4fd882bfc6f7ec53d30fa197b8ee22dc"}, - {file = "numpy-1.24.4-cp38-cp38-win32.whl", hash = "sha256:4602244f345453db537be5314d3983dbf5834a9701b7723ec28923e2889e0bb2"}, - {file = "numpy-1.24.4-cp38-cp38-win_amd64.whl", hash = "sha256:692f2e0f55794943c5bfff12b3f56f99af76f902fc47487bdfe97856de51a706"}, - {file = "numpy-1.24.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2541312fbf09977f3b3ad449c4e5f4bb55d0dbf79226d7724211acc905049400"}, - {file = "numpy-1.24.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:9667575fb6d13c95f1b36aca12c5ee3356bf001b714fc354eb5465ce1609e62f"}, - {file = "numpy-1.24.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f3a86ed21e4f87050382c7bc96571755193c4c1392490744ac73d660e8f564a9"}, - {file = "numpy-1.24.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d11efb4dbecbdf22508d55e48d9c8384db795e1b7b51ea735289ff96613ff74d"}, - {file = "numpy-1.24.4-cp39-cp39-win32.whl", hash = "sha256:6620c0acd41dbcb368610bb2f4d83145674040025e5536954782467100aa8835"}, - {file = "numpy-1.24.4-cp39-cp39-win_amd64.whl", hash = "sha256:befe2bf740fd8373cf56149a5c23a0f601e82869598d41f8e188a0e9869926f8"}, - {file = "numpy-1.24.4-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:31f13e25b4e304632a4619d0e0777662c2ffea99fcae2029556b17d8ff958aef"}, - {file = "numpy-1.24.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95f7ac6540e95bc440ad77f56e520da5bf877f87dca58bd095288dce8940532a"}, - {file = "numpy-1.24.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:e98f220aa76ca2a977fe435f5b04d7b3470c0a2e6312907b37ba6068f26787f2"}, - {file = "numpy-1.24.4.tar.gz", hash = "sha256:80f5e3a4e498641401868df4208b74581206afbee7cf7b8329daae82676d9463"}, + {file = "numpy-1.26.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:82e871307a6331b5f09efda3c22e03c095d957f04bf6bc1804f30048d0e5e7af"}, + {file = "numpy-1.26.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cdd9ec98f0063d93baeb01aad472a1a0840dee302842a2746a7a8e92968f9575"}, + {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d78f269e0c4fd365fc2992c00353e4530d274ba68f15e968d8bc3c69ce5f5244"}, + {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8ab9163ca8aeb7fd32fe93866490654d2f7dda4e61bc6297bf72ce07fdc02f67"}, + {file = "numpy-1.26.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:78ca54b2f9daffa5f323f34cdf21e1d9779a54073f0018a3094ab907938331a2"}, + {file = "numpy-1.26.1-cp310-cp310-win32.whl", hash = "sha256:d1cfc92db6af1fd37a7bb58e55c8383b4aa1ba23d012bdbba26b4bcca45ac297"}, + {file = "numpy-1.26.1-cp310-cp310-win_amd64.whl", hash = "sha256:d2984cb6caaf05294b8466966627e80bf6c7afd273279077679cb010acb0e5ab"}, + {file = "numpy-1.26.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cd7837b2b734ca72959a1caf3309457a318c934abef7a43a14bb984e574bbb9a"}, + {file = "numpy-1.26.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1c59c046c31a43310ad0199d6299e59f57a289e22f0f36951ced1c9eac3665b9"}, + {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d58e8c51a7cf43090d124d5073bc29ab2755822181fcad978b12e144e5e5a4b3"}, + {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6081aed64714a18c72b168a9276095ef9155dd7888b9e74b5987808f0dd0a974"}, + {file = "numpy-1.26.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:97e5d6a9f0702c2863aaabf19f0d1b6c2628fbe476438ce0b5ce06e83085064c"}, + {file = "numpy-1.26.1-cp311-cp311-win32.whl", hash = "sha256:b9d45d1dbb9de84894cc50efece5b09939752a2d75aab3a8b0cef6f3a35ecd6b"}, + {file = "numpy-1.26.1-cp311-cp311-win_amd64.whl", hash = "sha256:3649d566e2fc067597125428db15d60eb42a4e0897fc48d28cb75dc2e0454e53"}, + {file = "numpy-1.26.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1d1bd82d539607951cac963388534da3b7ea0e18b149a53cf883d8f699178c0f"}, + {file = "numpy-1.26.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:afd5ced4e5a96dac6725daeb5242a35494243f2239244fad10a90ce58b071d24"}, + {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a03fb25610ef560a6201ff06df4f8105292ba56e7cdd196ea350d123fc32e24e"}, + {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dcfaf015b79d1f9f9c9fd0731a907407dc3e45769262d657d754c3a028586124"}, + {file = "numpy-1.26.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e509cbc488c735b43b5ffea175235cec24bbc57b227ef1acc691725beb230d1c"}, + {file = "numpy-1.26.1-cp312-cp312-win32.whl", hash = "sha256:af22f3d8e228d84d1c0c44c1fbdeb80f97a15a0abe4f080960393a00db733b66"}, + {file = "numpy-1.26.1-cp312-cp312-win_amd64.whl", hash = "sha256:9f42284ebf91bdf32fafac29d29d4c07e5e9d1af862ea73686581773ef9e73a7"}, + {file = "numpy-1.26.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bb894accfd16b867d8643fc2ba6c8617c78ba2828051e9a69511644ce86ce83e"}, + {file = "numpy-1.26.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e44ccb93f30c75dfc0c3aa3ce38f33486a75ec9abadabd4e59f114994a9c4617"}, + {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9696aa2e35cc41e398a6d42d147cf326f8f9d81befcb399bc1ed7ffea339b64e"}, + {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b411040beead47a228bde3b2241100454a6abde9df139ed087bd73fc0a4908"}, + {file = "numpy-1.26.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1e11668d6f756ca5ef534b5be8653d16c5352cbb210a5c2a79ff288e937010d5"}, + {file = "numpy-1.26.1-cp39-cp39-win32.whl", hash = "sha256:d1d2c6b7dd618c41e202c59c1413ef9b2c8e8a15f5039e344af64195459e3104"}, + {file = "numpy-1.26.1-cp39-cp39-win_amd64.whl", hash = "sha256:59227c981d43425ca5e5c01094d59eb14e8772ce6975d4b2fc1e106a833d5ae2"}, + {file = "numpy-1.26.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:06934e1a22c54636a059215d6da99e23286424f316fddd979f5071093b648668"}, + {file = "numpy-1.26.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76ff661a867d9272cd2a99eed002470f46dbe0943a5ffd140f49be84f68ffc42"}, + {file = "numpy-1.26.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:6965888d65d2848e8768824ca8288db0a81263c1efccec881cb35a0d805fcd2f"}, + {file = "numpy-1.26.1.tar.gz", hash = "sha256:c8c6c72d4a9f831f328efb1312642a1cafafaa88981d9ab76368d50d07d93cbe"}, ] [[package]] name = "packaging" -version = "23.1" +version = "23.2" description = "Core utilities for Python packages" optional = false python-versions = ">=3.7" files = [ - {file = "packaging-23.1-py3-none-any.whl", hash = "sha256:994793af429502c4ea2ebf6bf664629d07c1a9fe974af92966e4b8d2df7edc61"}, - {file = "packaging-23.1.tar.gz", hash = "sha256:a392980d2b6cffa644431898be54b0045151319d1e7ec34f0cfed48767dd334f"}, + {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"}, + {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"}, ] [[package]] name = "pandas" -version = "2.0.3" +version = "2.1.2" description = "Powerful data structures for data analysis, time series, and statistics" optional = false -python-versions = ">=3.8" +python-versions = ">=3.9" files = [ - {file = "pandas-2.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e4c7c9f27a4185304c7caf96dc7d91bc60bc162221152de697c98eb0b2648dd8"}, - {file = "pandas-2.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f167beed68918d62bffb6ec64f2e1d8a7d297a038f86d4aed056b9493fca407f"}, - {file = "pandas-2.0.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ce0c6f76a0f1ba361551f3e6dceaff06bde7514a374aa43e33b588ec10420183"}, - {file = "pandas-2.0.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba619e410a21d8c387a1ea6e8a0e49bb42216474436245718d7f2e88a2f8d7c0"}, - {file = "pandas-2.0.3-cp310-cp310-win32.whl", hash = "sha256:3ef285093b4fe5058eefd756100a367f27029913760773c8bf1d2d8bebe5d210"}, - {file = "pandas-2.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:9ee1a69328d5c36c98d8e74db06f4ad518a1840e8ccb94a4ba86920986bb617e"}, - {file = "pandas-2.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b084b91d8d66ab19f5bb3256cbd5ea661848338301940e17f4492b2ce0801fe8"}, - {file = "pandas-2.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37673e3bdf1551b95bf5d4ce372b37770f9529743d2498032439371fc7b7eb26"}, - {file = "pandas-2.0.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9cb1e14fdb546396b7e1b923ffaeeac24e4cedd14266c3497216dd4448e4f2d"}, - {file = "pandas-2.0.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d9cd88488cceb7635aebb84809d087468eb33551097d600c6dad13602029c2df"}, - {file = "pandas-2.0.3-cp311-cp311-win32.whl", hash = "sha256:694888a81198786f0e164ee3a581df7d505024fbb1f15202fc7db88a71d84ebd"}, - {file = "pandas-2.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:6a21ab5c89dcbd57f78d0ae16630b090eec626360085a4148693def5452d8a6b"}, - {file = "pandas-2.0.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9e4da0d45e7f34c069fe4d522359df7d23badf83abc1d1cef398895822d11061"}, - {file = "pandas-2.0.3-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:32fca2ee1b0d93dd71d979726b12b61faa06aeb93cf77468776287f41ff8fdc5"}, - {file = "pandas-2.0.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:258d3624b3ae734490e4d63c430256e716f488c4fcb7c8e9bde2d3aa46c29089"}, - {file = "pandas-2.0.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9eae3dc34fa1aa7772dd3fc60270d13ced7346fcbcfee017d3132ec625e23bb0"}, - {file = "pandas-2.0.3-cp38-cp38-win32.whl", hash = "sha256:f3421a7afb1a43f7e38e82e844e2bca9a6d793d66c1a7f9f0ff39a795bbc5e02"}, - {file = "pandas-2.0.3-cp38-cp38-win_amd64.whl", hash = "sha256:69d7f3884c95da3a31ef82b7618af5710dba95bb885ffab339aad925c3e8ce78"}, - {file = "pandas-2.0.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:5247fb1ba347c1261cbbf0fcfba4a3121fbb4029d95d9ef4dc45406620b25c8b"}, - {file = "pandas-2.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:81af086f4543c9d8bb128328b5d32e9986e0c84d3ee673a2ac6fb57fd14f755e"}, - {file = "pandas-2.0.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1994c789bf12a7c5098277fb43836ce090f1073858c10f9220998ac74f37c69b"}, - {file = "pandas-2.0.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ec591c48e29226bcbb316e0c1e9423622bc7a4eaf1ef7c3c9fa1a3981f89641"}, - {file = "pandas-2.0.3-cp39-cp39-win32.whl", hash = "sha256:04dbdbaf2e4d46ca8da896e1805bc04eb85caa9a82e259e8eed00254d5e0c682"}, - {file = "pandas-2.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:1168574b036cd8b93abc746171c9b4f1b83467438a5e45909fed645cf8692dbc"}, - {file = "pandas-2.0.3.tar.gz", hash = "sha256:c02f372a88e0d17f36d3093a644c73cfc1788e876a7c4bcb4020a77512e2043c"}, + {file = "pandas-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:24057459f19db9ebb02984c6fdd164a970b31a95f38e4a49cf7615b36a1b532c"}, + {file = "pandas-2.1.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a6cf8fcc8a63d333970b950a7331a30544cf59b1a97baf0a7409e09eafc1ac38"}, + {file = "pandas-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ae6ffbd9d614c20d028c7117ee911fc4e266b4dca2065d5c5909e401f8ff683"}, + {file = "pandas-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eff794eeb7883c5aefb1ed572e7ff533ae779f6c6277849eab9e77986e352688"}, + {file = "pandas-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:02954e285e8e2f4006b6f22be6f0df1f1c3c97adbb7ed211c6b483426f20d5c8"}, + {file = "pandas-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:5b40c9f494e1f27588c369b9e4a6ca19cd924b3a0e1ef9ef1a8e30a07a438f43"}, + {file = "pandas-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:08d287b68fd28906a94564f15118a7ca8c242e50ae7f8bd91130c362b2108a81"}, + {file = "pandas-2.1.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bbd98dcdcd32f408947afdb3f7434fade6edd408c3077bbce7bd840d654d92c6"}, + {file = "pandas-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e90c95abb3285d06f6e4feedafc134306a8eced93cb78e08cf50e224d5ce22e2"}, + {file = "pandas-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:52867d69a54e71666cd184b04e839cff7dfc8ed0cd6b936995117fdae8790b69"}, + {file = "pandas-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8d0382645ede2fde352da2a885aac28ec37d38587864c0689b4b2361d17b1d4c"}, + {file = "pandas-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:65177d1c519b55e5b7f094c660ed357bb7d86e799686bb71653b8a4803d8ff0d"}, + {file = "pandas-2.1.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5aa6b86802e8cf7716bf4b4b5a3c99b12d34e9c6a9d06dad254447a620437931"}, + {file = "pandas-2.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d594e2ce51b8e0b4074e6644758865dc2bb13fd654450c1eae51201260a539f1"}, + {file = "pandas-2.1.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3223f997b6d2ebf9c010260cf3d889848a93f5d22bb4d14cd32638b3d8bba7ad"}, + {file = "pandas-2.1.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc4944dc004ca6cc701dfa19afb8bdb26ad36b9bed5bcec617d2a11e9cae6902"}, + {file = "pandas-2.1.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3f76280ce8ec216dde336e55b2b82e883401cf466da0fe3be317c03fb8ee7c7d"}, + {file = "pandas-2.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:7ad20d24acf3a0042512b7e8d8fdc2e827126ed519d6bd1ed8e6c14ec8a2c813"}, + {file = "pandas-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:021f09c15e1381e202d95d4a21ece8e7f2bf1388b6d7e9cae09dfe27bd2043d1"}, + {file = "pandas-2.1.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e7f12b2de0060b0b858cfec0016e7d980ae5bae455a1746bfcc70929100ee633"}, + {file = "pandas-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:83c166b9bb27c1715bed94495d9598a7f02950b4749dba9349c1dd2cbf10729d"}, + {file = "pandas-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:25c9976c17311388fcd953cb3d0697999b2205333f4e11e669d90ff8d830d429"}, + {file = "pandas-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:851b5afbb0d62f6129ae891b533aa508cc357d5892c240c91933d945fff15731"}, + {file = "pandas-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:e78507adcc730533619de07bfdd1c62b2918a68cd4419ea386e28abf7f6a1e5c"}, + {file = "pandas-2.1.2.tar.gz", hash = "sha256:52897edc2774d2779fbeb6880d2cfb305daa0b1a29c16b91f531a18918a6e0f3"}, ] [package.dependencies] numpy = [ - {version = ">=1.20.3", markers = "python_version < \"3.10\""}, - {version = ">=1.23.2", markers = "python_version >= \"3.11\""}, - {version = ">=1.21.0", markers = "python_version >= \"3.10\" and python_version < \"3.11\""}, + {version = ">=1.22.4,<2", markers = "python_version < \"3.11\""}, + {version = ">=1.23.2,<2", markers = "python_version == \"3.11\""}, + {version = ">=1.26.0,<2", markers = "python_version >= \"3.12\""}, ] python-dateutil = ">=2.8.2" pytz = ">=2020.1" tzdata = ">=2022.1" [package.extras] -all = ["PyQt5 (>=5.15.1)", "SQLAlchemy (>=1.4.16)", "beautifulsoup4 (>=4.9.3)", "bottleneck (>=1.3.2)", "brotlipy (>=0.7.0)", "fastparquet (>=0.6.3)", "fsspec (>=2021.07.0)", "gcsfs (>=2021.07.0)", "html5lib (>=1.1)", "hypothesis (>=6.34.2)", "jinja2 (>=3.0.0)", "lxml (>=4.6.3)", "matplotlib (>=3.6.1)", "numba (>=0.53.1)", "numexpr (>=2.7.3)", "odfpy (>=1.4.1)", "openpyxl (>=3.0.7)", "pandas-gbq (>=0.15.0)", "psycopg2 (>=2.8.6)", "pyarrow (>=7.0.0)", "pymysql (>=1.0.2)", "pyreadstat (>=1.1.2)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)", "python-snappy (>=0.6.0)", "pyxlsb (>=1.0.8)", "qtpy (>=2.2.0)", "s3fs (>=2021.08.0)", "scipy (>=1.7.1)", "tables (>=3.6.1)", "tabulate (>=0.8.9)", "xarray (>=0.21.0)", "xlrd (>=2.0.1)", "xlsxwriter (>=1.4.3)", "zstandard (>=0.15.2)"] -aws = ["s3fs (>=2021.08.0)"] -clipboard = ["PyQt5 (>=5.15.1)", "qtpy (>=2.2.0)"] -compression = ["brotlipy (>=0.7.0)", "python-snappy (>=0.6.0)", "zstandard (>=0.15.2)"] -computation = ["scipy (>=1.7.1)", "xarray (>=0.21.0)"] -excel = ["odfpy (>=1.4.1)", "openpyxl (>=3.0.7)", "pyxlsb (>=1.0.8)", "xlrd (>=2.0.1)", "xlsxwriter (>=1.4.3)"] +all = ["PyQt5 (>=5.15.6)", "SQLAlchemy (>=1.4.36)", "beautifulsoup4 (>=4.11.1)", "bottleneck (>=1.3.4)", "dataframe-api-compat (>=0.1.7)", "fastparquet (>=0.8.1)", "fsspec (>=2022.05.0)", "gcsfs (>=2022.05.0)", "html5lib (>=1.1)", "hypothesis (>=6.46.1)", "jinja2 (>=3.1.2)", "lxml (>=4.8.0)", "matplotlib (>=3.6.1)", "numba (>=0.55.2)", "numexpr (>=2.8.0)", "odfpy (>=1.4.1)", "openpyxl (>=3.0.10)", "pandas-gbq (>=0.17.5)", "psycopg2 (>=2.9.3)", "pyarrow (>=7.0.0)", "pymysql (>=1.0.2)", "pyreadstat (>=1.1.5)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)", "pyxlsb (>=1.0.9)", "qtpy (>=2.2.0)", "s3fs (>=2022.05.0)", "scipy (>=1.8.1)", "tables (>=3.7.0)", "tabulate (>=0.8.10)", "xarray (>=2022.03.0)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.3)", "zstandard (>=0.17.0)"] +aws = ["s3fs (>=2022.05.0)"] +clipboard = ["PyQt5 (>=5.15.6)", "qtpy (>=2.2.0)"] +compression = ["zstandard (>=0.17.0)"] +computation = ["scipy (>=1.8.1)", "xarray (>=2022.03.0)"] +consortium-standard = ["dataframe-api-compat (>=0.1.7)"] +excel = ["odfpy (>=1.4.1)", "openpyxl (>=3.0.10)", "pyxlsb (>=1.0.9)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.3)"] feather = ["pyarrow (>=7.0.0)"] -fss = ["fsspec (>=2021.07.0)"] -gcp = ["gcsfs (>=2021.07.0)", "pandas-gbq (>=0.15.0)"] -hdf5 = ["tables (>=3.6.1)"] -html = ["beautifulsoup4 (>=4.9.3)", "html5lib (>=1.1)", "lxml (>=4.6.3)"] -mysql = ["SQLAlchemy (>=1.4.16)", "pymysql (>=1.0.2)"] -output-formatting = ["jinja2 (>=3.0.0)", "tabulate (>=0.8.9)"] +fss = ["fsspec (>=2022.05.0)"] +gcp = ["gcsfs (>=2022.05.0)", "pandas-gbq (>=0.17.5)"] +hdf5 = ["tables (>=3.7.0)"] +html = ["beautifulsoup4 (>=4.11.1)", "html5lib (>=1.1)", "lxml (>=4.8.0)"] +mysql = ["SQLAlchemy (>=1.4.36)", "pymysql (>=1.0.2)"] +output-formatting = ["jinja2 (>=3.1.2)", "tabulate (>=0.8.10)"] parquet = ["pyarrow (>=7.0.0)"] -performance = ["bottleneck (>=1.3.2)", "numba (>=0.53.1)", "numexpr (>=2.7.1)"] +performance = ["bottleneck (>=1.3.4)", "numba (>=0.55.2)", "numexpr (>=2.8.0)"] plot = ["matplotlib (>=3.6.1)"] -postgresql = ["SQLAlchemy (>=1.4.16)", "psycopg2 (>=2.8.6)"] -spss = ["pyreadstat (>=1.1.2)"] -sql-other = ["SQLAlchemy (>=1.4.16)"] -test = ["hypothesis (>=6.34.2)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)"] -xml = ["lxml (>=4.6.3)"] +postgresql = ["SQLAlchemy (>=1.4.36)", "psycopg2 (>=2.9.3)"] +spss = ["pyreadstat (>=1.1.5)"] +sql-other = ["SQLAlchemy (>=1.4.36)"] +test = ["hypothesis (>=6.46.1)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)"] +xml = ["lxml (>=4.8.0)"] + +[[package]] +name = "pandas-stubs" +version = "2.1.1.230928" +description = "Type annotations for pandas" +optional = false +python-versions = ">=3.9" +files = [ + {file = "pandas_stubs-2.1.1.230928-py3-none-any.whl", hash = "sha256:992d97159e054ca3175ebe8321ac5616cf6502dd8218b03bb0eaf3c4f6939037"}, + {file = "pandas_stubs-2.1.1.230928.tar.gz", hash = "sha256:ce1691c71c5d67b8f332da87763f7f54650f46895d99964d588c3a5d79e2cacc"}, +] + +[package.dependencies] +numpy = {version = ">=1.26.0", markers = "python_version < \"3.13\""} +types-pytz = ">=2022.1.1" [[package]] name = "pdoc" @@ -598,7 +689,6 @@ files = [ ] [package.dependencies] -astunparse = {version = "*", markers = "python_version < \"3.9\""} Jinja2 = ">=2.11.0" MarkupSafe = "*" pygments = ">=2.12.0" @@ -608,17 +698,18 @@ dev = ["black", "hypothesis", "mypy", "pygments (>=2.14.0)", "pytest", "pytest-c [[package]] name = "pluggy" -version = "0.13.1" +version = "1.3.0" description = "plugin and hook calling mechanisms for python" optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +python-versions = ">=3.8" files = [ - {file = "pluggy-0.13.1-py2.py3-none-any.whl", hash = "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d"}, - {file = "pluggy-0.13.1.tar.gz", hash = "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0"}, + {file = "pluggy-1.3.0-py3-none-any.whl", hash = "sha256:d89c696a773f8bd377d18e5ecda92b7a3793cbe66c87060a6fb58c7b6e1061f7"}, + {file = "pluggy-1.3.0.tar.gz", hash = "sha256:cf61ae8f126ac6f7c451172cf30e3e43d3ca77615509771b3a984a0730651e12"}, ] [package.extras] dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] [[package]] name = "protobuf" @@ -779,6 +870,65 @@ files = [ {file = "pytz-2023.3.post1.tar.gz", hash = "sha256:7b4fddbeb94a1eba4b557da24f19fdf9db575192544270a9101d8509f9f43d7b"}, ] +[[package]] +name = "pyyaml" +version = "6.0.1" +description = "YAML parser and emitter for Python" +optional = false +python-versions = ">=3.6" +files = [ + {file = "PyYAML-6.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a"}, + {file = "PyYAML-6.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f"}, + {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"}, + {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"}, + {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"}, + {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"}, + {file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"}, + {file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"}, + {file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"}, + {file = "PyYAML-6.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab"}, + {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"}, + {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"}, + {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"}, + {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"}, + {file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"}, + {file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"}, + {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"}, + {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"}, + {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"}, + {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"}, + {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"}, + {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"}, + {file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"}, + {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"}, + {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"}, + {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd"}, + {file = "PyYAML-6.0.1-cp36-cp36m-win32.whl", hash = "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585"}, + {file = "PyYAML-6.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa"}, + {file = "PyYAML-6.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3"}, + {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27"}, + {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3"}, + {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c"}, + {file = "PyYAML-6.0.1-cp37-cp37m-win32.whl", hash = "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba"}, + {file = "PyYAML-6.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867"}, + {file = "PyYAML-6.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595"}, + {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"}, + {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"}, + {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"}, + {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"}, + {file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"}, + {file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"}, + {file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"}, + {file = "PyYAML-6.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859"}, + {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"}, + {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"}, + {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"}, + {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"}, + {file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"}, + {file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"}, + {file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"}, +] + [[package]] name = "requests" version = "2.31.0" @@ -802,21 +952,22 @@ use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] [[package]] name = "responses" -version = "0.10.15" +version = "0.24.0" description = "A utility library for mocking out the `requests` Python library." optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +python-versions = ">=3.8" files = [ - {file = "responses-0.10.15-py2.py3-none-any.whl", hash = "sha256:af94d28cdfb48ded0ad82a5216616631543650f440334a693479b8991a6594a2"}, - {file = "responses-0.10.15.tar.gz", hash = "sha256:7bb697a5fedeb41d81e8b87f152d453d5cab42dcd1691b6a7d6097e94d33f373"}, + {file = "responses-0.24.0-py3-none-any.whl", hash = "sha256:060be153c270c06fa4d22c1ef8865fdef43902eb595204deeef736cddb62d353"}, + {file = "responses-0.24.0.tar.gz", hash = "sha256:3df82f7d4dcd3e5f61498181aadb4381f291da25c7506c47fe8cb68ce29203e7"}, ] [package.dependencies] -requests = ">=2.0" -six = "*" +pyyaml = "*" +requests = ">=2.30.0,<3.0" +urllib3 = ">=1.25.10,<3.0" [package.extras] -tests = ["coverage (>=3.7.1,<5.0.0)", "flake8", "pytest", "pytest (>=4.6,<5.0)", "pytest-cov", "pytest-localserver"] +tests = ["coverage (>=6.0.0)", "flake8", "mypy", "pytest (>=7.0.0)", "pytest-asyncio", "pytest-cov", "pytest-httpserver", "tomli", "tomli-w", "types-PyYAML", "types-requests"] [[package]] name = "six" @@ -860,6 +1011,64 @@ notebook = ["ipywidgets (>=6)"] slack = ["slack-sdk"] telegram = ["requests"] +[[package]] +name = "types-protobuf" +version = "4.24.0.4" +description = "Typing stubs for protobuf" +optional = false +python-versions = ">=3.7" +files = [ + {file = "types-protobuf-4.24.0.4.tar.gz", hash = "sha256:57ab42cb171dfdba2c74bb5b50c250478538cc3c5ed95b8b368929ad0c9f90a5"}, + {file = "types_protobuf-4.24.0.4-py3-none-any.whl", hash = "sha256:131ab7d0cbc9e444bc89c994141327dcce7bcaeded72b1acb72a94827eb9c7af"}, +] + +[[package]] +name = "types-pytz" +version = "2023.3.1.1" +description = "Typing stubs for pytz" +optional = false +python-versions = "*" +files = [ + {file = "types-pytz-2023.3.1.1.tar.gz", hash = "sha256:cc23d0192cd49c8f6bba44ee0c81e4586a8f30204970fc0894d209a6b08dab9a"}, + {file = "types_pytz-2023.3.1.1-py3-none-any.whl", hash = "sha256:1999a123a3dc0e39a2ef6d19f3f8584211de9e6a77fe7a0259f04a524e90a5cf"}, +] + +[[package]] +name = "types-requests" +version = "2.31.0.10" +description = "Typing stubs for requests" +optional = false +python-versions = ">=3.7" +files = [ + {file = "types-requests-2.31.0.10.tar.gz", hash = "sha256:dc5852a76f1eaf60eafa81a2e50aefa3d1f015c34cf0cba130930866b1b22a92"}, + {file = "types_requests-2.31.0.10-py3-none-any.whl", hash = "sha256:b32b9a86beffa876c0c3ac99a4cd3b8b51e973fb8e3bd4e0a6bb32c7efad80fc"}, +] + +[package.dependencies] +urllib3 = ">=2" + +[[package]] +name = "types-tqdm" +version = "4.66.0.4" +description = "Typing stubs for tqdm" +optional = false +python-versions = ">=3.7" +files = [ + {file = "types-tqdm-4.66.0.4.tar.gz", hash = "sha256:a2f0ebd4cfd48f4914395819a176d7947387e1b98f9228fca38f8cac1b59891c"}, + {file = "types_tqdm-4.66.0.4-py3-none-any.whl", hash = "sha256:8eda4c5123dd66985a4cb44268705cfa18beb32d66772271ae185e92b8b10c40"}, +] + +[[package]] +name = "types-urllib3" +version = "1.26.25.14" +description = "Typing stubs for urllib3" +optional = false +python-versions = "*" +files = [ + {file = "types-urllib3-1.26.25.14.tar.gz", hash = "sha256:229b7f577c951b8c1b92c1bc2b2fdb0b49847bd2af6d1cc2a2e3dd340f3bda8f"}, + {file = "types_urllib3-1.26.25.14-py3-none-any.whl", hash = "sha256:9683bbb7fb72e32bfe9d2be6e04875fbe1b3eeec3cbb4ea231435aa7fd6b4f0e"}, +] + [[package]] name = "typing-extensions" version = "4.8.0" @@ -884,19 +1093,20 @@ files = [ [[package]] name = "urllib3" -version = "1.25.3" +version = "2.0.7" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4" +python-versions = ">=3.7" files = [ - {file = "urllib3-1.25.3-py2.py3-none-any.whl", hash = "sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1"}, - {file = "urllib3-1.25.3.tar.gz", hash = "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232"}, + {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"}, + {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"}, ] [package.extras] -brotli = ["brotlipy (>=0.6.0)"] -secure = ["certifi", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "ipaddress", "pyOpenSSL (>=0.14)"] -socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] +brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] +secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["zstandard (>=0.18.0)"] [[package]] name = "urllib3-mock" @@ -912,24 +1122,10 @@ files = [ [package.extras] tests = ["flake8", "pytest", "pytest-cov", "requests"] -[[package]] -name = "wheel" -version = "0.41.2" -description = "A built-package format for Python" -optional = false -python-versions = ">=3.7" -files = [ - {file = "wheel-0.41.2-py3-none-any.whl", hash = "sha256:75909db2664838d015e3d9139004ee16711748a52c8f336b52882266540215d8"}, - {file = "wheel-0.41.2.tar.gz", hash = "sha256:0c5ac5ff2afb79ac23ab82bab027a0be7b5dbcf2e54dc50efe4bf507de1f7985"}, -] - -[package.extras] -test = ["pytest (>=6.0.0)", "setuptools (>=65)"] - [extras] grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio", "lz4", "protobuf"] [metadata] lock-version = "2.0" -python-versions = ">=3.8,<4.0" -content-hash = "e0307950e6c3594275fa15a56ec7302cce85bccc7a767d29cacb2bcc40706841" +python-versions = ">=3.9,<3.13" +content-hash = "fa552381e2fb77005a53c49211b836d403c6796ebc1f4e7b614852cc5712c1e7" diff --git a/pyproject.toml b/pyproject.toml index a991bae64..e1dce11fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,11 +54,11 @@ classifiers=[ ] [tool.poetry.dependencies] -python = ">=3.8,<4.0" +python = ">=3.9,<3.13" requests = "^2.31.0" typing-extensions = ">=3.7.4" python-dateutil = ">=2.5.3" -urllib3 = "1.25.3" +urllib3 = "2.0.7" tqdm = ">=4.64.1" grpcio = { version = ">=1.44.0", optional = true } grpc-gateway-protoc-gen-openapiv2 = { version = "0.1.0", optional = true } @@ -77,15 +77,15 @@ pytest-timeout = "1.4.2" urllib3_mock = "0.3.3" responses = ">=0.8.1" pandas = ">=1.3.5" +mypy = "^1.6.1" +types-requests = "^2.31.0.10" +types-urllib3 = "^1.26.25.14" +grpc-stubs = "^1.53.0.3" +pandas-stubs = "^2.1.1.230928" +types-tqdm = "^4.66.0.3" +types-protobuf = "^4.24.0.4" [tool.poetry.extras] -# Poetry's concept of extras is what allows us to separate the gRPC dependencies, -# which will only be installed if you run `poetry install --extras "grpc"`, -# from the base dependencies. -# -# Note that Poetry expects the dependencies to be defined in either tool.poetry.dependencies -# or tool.poetry.group.dev.dependencies, but they're only referenced by name in the grpc entry under -# tool.poetry.extras grpc = ["grpcio", "grpc-gateway-protoc-gen-openapiv2", "googleapis-common-protos", "lz4", "protobuf"] [build-system] diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index bc65abe0d..aebd002c6 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -30,34 +30,30 @@ def test_init_with_environment_vars(self): os.environ["PINECONE_API_KEY"] = "test-api-key" os.environ["PINECONE_CONTROLLER_HOST"] = "test-controller-host" - config = PineconeConfig() + config = PineconeConfig.build() - assert config.API_KEY == "test-api-key" - assert config.HOST == "test-controller-host" + assert config.api_key == "test-api-key" + assert config.host == "test-controller-host" def test_init_with_positional_args(self): api_key = "my-api-key" host = "my-controller-host" - config = PineconeConfig(api_key, host) + config = PineconeConfig.build(api_key, host) - assert config.API_KEY == api_key - assert config.HOST == host + assert config.api_key == api_key + assert config.host == host def test_init_with_kwargs(self): api_key = "my-api-key" controller_host = "my-controller-host" openapi_config = OpenApiConfiguration(api_key="openapi-api-key") - config = PineconeConfig(api_key=api_key, host=controller_host, openapi_config=openapi_config) + config = PineconeConfig.build(api_key=api_key, host=controller_host, openapi_config=openapi_config) - assert config.API_KEY == api_key - assert config.HOST == controller_host - assert config.OPENAPI_CONFIG == openapi_config - - def test_init_with_mispelled_kwargs(self, caplog): - PineconeConfig(api_key='my-api-key', unknown_kwarg='bogus') - assert "__init__ had unexpected keyword argument(s): unknown_kwarg" in caplog.text + assert config.api_key == api_key + assert config.host == controller_host + assert config.openapi_config == openapi_config def test_resolution_order_kwargs_over_env_vars(self): """ @@ -70,11 +66,11 @@ def test_resolution_order_kwargs_over_env_vars(self): api_key = "kwargs-api-key" controller_host = "kwargs-controller-host" - config = PineconeConfig(api_key=api_key, host=controller_host) + config = PineconeConfig.build(api_key=api_key, host=controller_host) - assert config.API_KEY == api_key - assert config.HOST == controller_host + assert config.api_key == api_key + assert config.host == controller_host def test_errors_when_no_api_key_is_present(self): with pytest.raises(PineconeConfigurationError): - PineconeConfig() \ No newline at end of file + PineconeConfig.build() \ No newline at end of file From dbbed9442ac0f8de32b4fac189916560c7305f68 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 10 Nov 2023 09:03:30 -0500 Subject: [PATCH 10/39] Regenerate client with updated openapi spec (#243) ## Problem Missed a couple fields in the last iteration ## Solution Regenerate client, update tests. --- pinecone/control/pinecone.py | 34 +-- .../core/client/api/index_operations_api.py | 35 +-- pinecone/core/client/model/collection_meta.py | 38 ++- .../client/model/create_collection_request.py | 4 +- pinecone/core/client/model/create_request.py | 31 +- pinecone/core/client/model/index_list_meta.py | 286 ++++++++++++++++++ pinecone/core/client/model/index_meta.py | 20 +- .../core/client/model/index_meta_database.py | 40 ++- .../core/client/model/index_meta_status.py | 32 +- .../core/client/model/inline_response200.py | 262 ++++++++++++++++ pinecone/core/client/models/__init__.py | 2 + 11 files changed, 704 insertions(+), 80 deletions(-) create mode 100644 pinecone/core/client/model/index_list_meta.py create mode 100644 pinecone/core/client/model/inline_response200.py diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 7f95bff3d..7155b08d4 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -49,6 +49,7 @@ def create_index( cloud: str, region: str, capacity_mode: str, + environment: Optional[str] = None, timeout: Optional[int] = None, index_type: str = "approximated", metric: str = "cosine", @@ -56,7 +57,7 @@ def create_index( shards: int = 1, pods: int = 1, pod_type: str = "p1", - index_config: Optional[dict] = None, + index_config: Optional[dict] = {}, metadata_config: Optional[dict] = None, source_collection: str = "", ): @@ -65,9 +66,15 @@ def create_index( :param name: the name of the index. :type name: str :param dimension: the dimension of vectors that would be inserted in the index + :type dimension: int :param cloud: The cloud where you would like your index hosted. One of `{"aws", "gcp"}`. + :type cloud: str :param region: The region where you would like your index hosted. + :type region: str :param capacity_mode: The capacity mode for the index. One of `{"pod"}`. + :type capacity_mode: str + :param environment: The environment where you would like your index hosted, e.g. 'us-east1-gcp'. Find this value in the Pinecone web console along with your API keys. + :type environment: str, optional :param index_type: type of index, one of `{"approximated", "exact"}`, defaults to "approximated". The "approximated" index uses fast approximate search algorithms developed by Pinecone. The "exact" index uses accurate exact search algorithms. @@ -98,26 +105,13 @@ def create_index( :param timeout: Timeout for 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 """ - api_instance = self.index_api + create_args = locals() + del create_args["self"] + if environment is None: + del create_args["environment"] - api_instance.create_index( - create_request=CreateRequest( - name=name, - dimension=dimension, - cloud=cloud, - region=region, - capacity_mode=capacity_mode, - index_type=index_type, - metric=metric, - replicas=replicas, - shards=shards, - pods=pods, - pod_type=pod_type, - index_config=index_config or {}, - metadata_config=metadata_config, - source_collection=source_collection, - ) - ) + api_instance = self.index_api + api_instance.create_index(create_request=CreateRequest(**create_args)) def is_ready(): status = self._get_status(name) diff --git a/pinecone/core/client/api/index_operations_api.py b/pinecone/core/client/api/index_operations_api.py index 152af5ad2..0e31c7800 100644 --- a/pinecone/core/client/api/index_operations_api.py +++ b/pinecone/core/client/api/index_operations_api.py @@ -26,6 +26,7 @@ from pinecone.core.client.model.create_collection_request import CreateCollectionRequest from pinecone.core.client.model.create_request import CreateRequest from pinecone.core.client.model.index_meta import IndexMeta +from pinecone.core.client.model.inline_response200 import InlineResponse200 from pinecone.core.client.model.patch_request import PatchRequest @@ -81,7 +82,7 @@ def __configure_index( async_req (bool): execute request asynchronously Returns: - str + IndexMeta If the method is called asynchronously, returns the request thread. """ @@ -110,7 +111,7 @@ def __configure_index( self.configure_index = _Endpoint( settings={ - 'response_type': (str,), + 'response_type': (IndexMeta,), 'auth': [ 'ApiKeyAuth' ], @@ -119,7 +120,7 @@ def __configure_index( 'http_method': 'PATCH', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -168,7 +169,7 @@ def __configure_index( }, headers_map={ 'accept': [ - 'text/plain' + 'application/json' ], 'content_type': [ 'application/json' @@ -251,7 +252,7 @@ def __create_collection( 'http_method': 'POST', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -340,7 +341,7 @@ def __create_index( async_req (bool): execute request asynchronously Returns: - str + IndexMeta If the method is called asynchronously, returns the request thread. """ @@ -367,7 +368,7 @@ def __create_index( self.create_index = _Endpoint( settings={ - 'response_type': (str,), + 'response_type': (IndexMeta,), 'auth': [ 'ApiKeyAuth' ], @@ -376,7 +377,7 @@ def __create_index( 'http_method': 'POST', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -418,7 +419,7 @@ def __create_index( }, headers_map={ 'accept': [ - 'text/plain' + 'application/json' ], 'content_type': [ 'application/json' @@ -505,7 +506,7 @@ def __delete_collection( 'http_method': 'DELETE', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -635,7 +636,7 @@ def __delete_index( 'http_method': 'DELETE', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -765,7 +766,7 @@ def __describe_collection( 'http_method': 'GET', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -895,7 +896,7 @@ def __describe_index( 'http_method': 'GET', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -1020,7 +1021,7 @@ def __list_collections( 'http_method': 'GET', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { @@ -1102,7 +1103,7 @@ def __list_indexes( async_req (bool): execute request asynchronously Returns: - [str] + InlineResponse200 If the method is called asynchronously, returns the request thread. """ @@ -1129,7 +1130,7 @@ def __list_indexes( self.list_indexes = _Endpoint( settings={ - 'response_type': ([str],), + 'response_type': (InlineResponse200,), 'auth': [ 'ApiKeyAuth' ], @@ -1138,7 +1139,7 @@ def __list_indexes( 'http_method': 'GET', 'servers': [ { - 'url': "https://controller.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", 'variables': { 'environment': { diff --git a/pinecone/core/client/model/collection_meta.py b/pinecone/core/client/model/collection_meta.py index cc3bfa5f1..9f33d5ef0 100644 --- a/pinecone/core/client/model/collection_meta.py +++ b/pinecone/core/client/model/collection_meta.py @@ -109,9 +109,16 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, size, status, dimension, vector_count, *args, **kwargs): # noqa: E501 """CollectionMeta - a model defined in OpenAPI + Args: + name (str): + size (int): The size of the collection in bytes. + status (str): The status of the collection. + dimension (int): The dimension of the records stored in the collection + vector_count (int): The number of records stored in the collection + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -143,11 +150,6 @@ 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,) - name (str): [optional] # noqa: E501 - size (int): The size of the collection in bytes.. [optional] # noqa: E501 - status (str): The status of the collection.. [optional] # noqa: E501 - dimension (int): [optional] # noqa: E501 - vector_count (int): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -175,6 +177,11 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.name = name + self.size = size + self.status = status + self.dimension = dimension + self.vector_count = vector_count for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -195,9 +202,16 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, name, size, status, dimension, vector_count, *args, **kwargs): # noqa: E501 """CollectionMeta - a model defined in OpenAPI + Args: + name (str): + size (int): The size of the collection in bytes. + status (str): The status of the collection. + dimension (int): The dimension of the records stored in the collection + vector_count (int): The number of records stored in the collection + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -229,11 +243,6 @@ 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,) - name (str): [optional] # noqa: E501 - size (int): The size of the collection in bytes.. [optional] # noqa: E501 - status (str): The status of the collection.. [optional] # noqa: E501 - dimension (int): [optional] # noqa: E501 - vector_count (int): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -259,6 +268,11 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.name = name + self.size = size + self.status = status + self.dimension = dimension + self.vector_count = vector_count for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/create_collection_request.py b/pinecone/core/client/model/create_collection_request.py index ac5474413..6cf24b7a7 100644 --- a/pinecone/core/client/model/create_collection_request.py +++ b/pinecone/core/client/model/create_collection_request.py @@ -108,7 +108,7 @@ def _from_openapi_data(cls, name, source, *args, **kwargs): # noqa: E501 Args: name (str): The name of the collection to be created. - source (str): The name of the source index to be used as the source for the collection. + source (str): The name of the index to be used as the source for the collection. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -195,7 +195,7 @@ def __init__(self, name, source, *args, **kwargs): # noqa: E501 Args: name (str): The name of the collection to be created. - source (str): The name of the source index to be used as the source for the collection. + source (str): The name of the index to be used as the source for the collection. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/client/model/create_request.py b/pinecone/core/client/model/create_request.py index 0dbb9f900..e19d8d9e4 100644 --- a/pinecone/core/client/model/create_request.py +++ b/pinecone/core/client/model/create_request.py @@ -56,6 +56,11 @@ class CreateRequest(ModelNormal): """ allowed_values = { + ('cloud',): { + 'GCP': "gcp", + 'AWS': "aws", + 'AZURE': "azure", + }, } validations = { @@ -84,6 +89,10 @@ def openapi_types(): return { 'name': (str,), # noqa: E501 'dimension': (int,), # noqa: E501 + 'region': (str,), # noqa: E501 + 'cloud': (str,), # noqa: E501 + 'capacity_mode': (str,), # noqa: E501 + 'environment': (str,), # noqa: E501 'index_type': (str,), # noqa: E501 'metric': (str,), # noqa: E501 'pods': (int,), # noqa: E501 @@ -103,6 +112,10 @@ def discriminator(): attribute_map = { 'name': 'name', # noqa: E501 'dimension': 'dimension', # noqa: E501 + 'region': 'region', # noqa: E501 + 'cloud': 'cloud', # noqa: E501 + 'capacity_mode': 'capacity_mode', # noqa: E501 + 'environment': 'environment', # noqa: E501 'index_type': 'index_type', # noqa: E501 'metric': 'metric', # noqa: E501 'pods': 'pods', # noqa: E501 @@ -121,12 +134,15 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, dimension, region, cloud, capacity_mode, *args, **kwargs): # noqa: E501 """CreateRequest - a model defined in OpenAPI Args: name (str): The name of the index to be created. The maximum length is 45 characters. dimension (int): The dimensions of the vectors to be inserted in the index + region (str): The region where you would like your index to be created + cloud (str): The public cloud where you would like your index hosted + capacity_mode (str): The capacity mode for the index. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -159,6 +175,7 @@ def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + environment (str): The environment where you would like your index to be created. [optional] # noqa: E501 index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 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 pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 @@ -197,6 +214,9 @@ def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 self.name = name self.dimension = dimension + self.region = region + self.cloud = cloud + self.capacity_mode = capacity_mode for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -217,12 +237,15 @@ def _from_openapi_data(cls, name, dimension, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, name, dimension, *args, **kwargs): # noqa: E501 + def __init__(self, name, dimension, region, cloud, capacity_mode, *args, **kwargs): # noqa: E501 """CreateRequest - a model defined in OpenAPI Args: name (str): The name of the index to be created. The maximum length is 45 characters. dimension (int): The dimensions of the vectors to be inserted in the index + region (str): The region where you would like your index to be created + cloud (str): The public cloud where you would like your index hosted + capacity_mode (str): The capacity mode for the index. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -255,6 +278,7 @@ def __init__(self, name, dimension, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + environment (str): The environment where you would like your index to be created. [optional] # noqa: E501 index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 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 pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 @@ -291,6 +315,9 @@ def __init__(self, name, dimension, *args, **kwargs): # noqa: E501 self.name = name self.dimension = dimension + self.region = region + self.cloud = cloud + self.capacity_mode = capacity_mode for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/index_list_meta.py b/pinecone/core/client/model/index_list_meta.py new file mode 100644 index 000000000..7cfbd92d9 --- /dev/null +++ b/pinecone/core/client/model/index_list_meta.py @@ -0,0 +1,286 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class IndexListMeta(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'metric': (str,), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'capacity_mode': (str,), # noqa: E501 + 'host': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'metric': 'metric', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'capacity_mode': 'capacity_mode', # noqa: E501 + 'host': 'host', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, metric, dimension, capacity_mode, host, *args, **kwargs): # noqa: E501 + """IndexListMeta - a model defined in OpenAPI + + Args: + name (str): + metric (str): + dimension (int): + capacity_mode (str): + host (str): + + 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 ApiTypeError( + "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.metric = metric + self.dimension = dimension + self.capacity_mode = capacity_mode + self.host = host + 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, metric, dimension, capacity_mode, host, *args, **kwargs): # noqa: E501 + """IndexListMeta - a model defined in OpenAPI + + Args: + name (str): + metric (str): + dimension (int): + capacity_mode (str): + host (str): + + 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 ApiTypeError( + "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.metric = metric + self.dimension = dimension + self.capacity_mode = capacity_mode + self.host = host + 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 ApiAttributeError(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/client/model/index_meta.py b/pinecone/core/client/model/index_meta.py index 5f17947dd..baac4d5c4 100644 --- a/pinecone/core/client/model/index_meta.py +++ b/pinecone/core/client/model/index_meta.py @@ -111,9 +111,13 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, database, status, *args, **kwargs): # noqa: E501 """IndexMeta - a model defined in OpenAPI + Args: + database (IndexMetaDatabase): + status (IndexMetaStatus): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -145,8 +149,6 @@ 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,) - database (IndexMetaDatabase): [optional] # noqa: E501 - status (IndexMetaStatus): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -174,6 +176,8 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.database = database + self.status = status for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -194,9 +198,13 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, database, status, *args, **kwargs): # noqa: E501 """IndexMeta - a model defined in OpenAPI + Args: + database (IndexMetaDatabase): + status (IndexMetaStatus): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -228,8 +236,6 @@ 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,) - database (IndexMetaDatabase): [optional] # noqa: E501 - status (IndexMetaStatus): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -255,6 +261,8 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.database = database + self.status = status for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/index_meta_database.py b/pinecone/core/client/model/index_meta_database.py index d93ddf057..22c9381f7 100644 --- a/pinecone/core/client/model/index_meta_database.py +++ b/pinecone/core/client/model/index_meta_database.py @@ -83,9 +83,10 @@ def openapi_types(): """ return { 'name': (str,), # noqa: E501 - 'dimension': (str,), # noqa: E501 - 'index_type': (str,), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'capacity_mode': (str,), # noqa: E501 'metric': (str,), # noqa: E501 + 'index_type': (str,), # noqa: E501 'pods': (int,), # noqa: E501 'replicas': (int,), # noqa: E501 'shards': (int,), # noqa: E501 @@ -102,8 +103,9 @@ def discriminator(): attribute_map = { 'name': 'name', # noqa: E501 'dimension': 'dimension', # noqa: E501 - 'index_type': 'index_type', # noqa: E501 + 'capacity_mode': 'capacity_mode', # noqa: E501 'metric': 'metric', # noqa: E501 + 'index_type': 'index_type', # noqa: E501 'pods': 'pods', # noqa: E501 'replicas': 'replicas', # noqa: E501 'shards': 'shards', # noqa: E501 @@ -119,10 +121,16 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, dimension, capacity_mode, *args, **kwargs): # noqa: E501 """IndexMetaDatabase - a model defined in OpenAPI + Args: + name (str): + dimension (int): + capacity_mode (str): + Keyword Args: + metric (str): defaults to "cosine" # 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. @@ -153,10 +161,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,) - name (str): [optional] # noqa: E501 - dimension (str): [optional] # noqa: E501 index_type (str): [optional] # noqa: E501 - metric (str): [optional] # noqa: E501 pods (int): [optional] # noqa: E501 replicas (int): [optional] # noqa: E501 shards (int): [optional] # noqa: E501 @@ -165,6 +170,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 """ + metric = kwargs.get('metric', "cosine") _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) @@ -190,6 +196,10 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.name = name + self.dimension = dimension + self.capacity_mode = capacity_mode + self.metric = metric for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -210,10 +220,16 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, name, dimension, capacity_mode, *args, **kwargs): # noqa: E501 """IndexMetaDatabase - a model defined in OpenAPI + Args: + name (str): + dimension (int): + capacity_mode (str): + Keyword Args: + metric (str): defaults to "cosine" # 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. @@ -244,10 +260,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,) - name (str): [optional] # noqa: E501 - dimension (str): [optional] # noqa: E501 index_type (str): [optional] # noqa: E501 - metric (str): [optional] # noqa: E501 pods (int): [optional] # noqa: E501 replicas (int): [optional] # noqa: E501 shards (int): [optional] # noqa: E501 @@ -256,6 +269,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 """ + metric = kwargs.get('metric', "cosine") _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) @@ -279,6 +293,10 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.name = name + self.dimension = dimension + self.capacity_mode = capacity_mode + self.metric = metric for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/index_meta_status.py b/pinecone/core/client/model/index_meta_status.py index 62abdbd66..43c28a839 100644 --- a/pinecone/core/client/model/index_meta_status.py +++ b/pinecone/core/client/model/index_meta_status.py @@ -117,9 +117,15 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, ready, state, host, port, *args, **kwargs): # noqa: E501 """IndexMetaStatus - a model defined in OpenAPI + Args: + ready (bool): + state (str): + host (str): + port (int): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -151,10 +157,6 @@ 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,) - ready (bool): [optional] # noqa: E501 - state (str): [optional] # noqa: E501 - host (str): [optional] # noqa: E501 - port (int): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -182,6 +184,10 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.ready = ready + self.state = state + self.host = host + self.port = port for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -202,9 +208,15 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, ready, state, host, port, *args, **kwargs): # noqa: E501 """IndexMetaStatus - a model defined in OpenAPI + Args: + ready (bool): + state (str): + host (str): + port (int): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -236,10 +248,6 @@ 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,) - ready (bool): [optional] # noqa: E501 - state (str): [optional] # noqa: E501 - host (str): [optional] # noqa: E501 - port (int): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -265,6 +273,10 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.ready = ready + self.state = state + self.host = host + self.port = port for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/inline_response200.py b/pinecone/core/client/model/inline_response200.py new file mode 100644 index 000000000..c7e991067 --- /dev/null +++ b/pinecone/core/client/model/inline_response200.py @@ -0,0 +1,262 @@ +""" + Pinecone API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: version not set + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.index_list_meta import IndexListMeta + globals()['IndexListMeta'] = IndexListMeta + + +class InlineResponse200(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'databases': ([IndexListMeta],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'databases': 'databases', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineResponse200 - 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,) + databases ([IndexListMeta]): [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 ApiTypeError( + "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 + """InlineResponse200 - 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,) + databases ([IndexListMeta]): [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 ApiTypeError( + "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 ApiAttributeError(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/client/models/__init__.py b/pinecone/core/client/models/__init__.py index 5c2079103..b514eb36f 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -18,9 +18,11 @@ from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse from pinecone.core.client.model.fetch_response import FetchResponse from pinecone.core.client.model.hnsw_config import HnswConfig +from pinecone.core.client.model.index_list_meta import IndexListMeta from pinecone.core.client.model.index_meta import IndexMeta from pinecone.core.client.model.index_meta_database import IndexMetaDatabase from pinecone.core.client.model.index_meta_status import IndexMetaStatus +from pinecone.core.client.model.inline_response200 import InlineResponse200 from pinecone.core.client.model.namespace_summary import NamespaceSummary from pinecone.core.client.model.patch_request import PatchRequest from pinecone.core.client.model.protobuf_any import ProtobufAny From 3d6cb0d63d2c3a821c8aa311a7b2bbae26bd7fae Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Sat, 18 Nov 2023 01:50:39 -0500 Subject: [PATCH 11/39] [spruce] Integration testing WIP (#244) ## Problem Want to implement end-to-end testing with the spruce branch. Most of these are currently failing, but going to merge them anyway so I can make a dev build with these changes. ## Solution - Add loads of tests under `test/integration` - Add workflow configuration to execute these in CI ## Type of Change - [x] Infrastructure change (CI configs, etc) ## Test Plan New tests should pass in CI --- .github/workflows/alpha-release.yaml | 1 + .github/workflows/nightly-release.yaml | 1 + .../workflows/nightly-spruce-dev-release.yaml | 1 + .github/workflows/pr.yaml | 1 + .github/workflows/release-spruce.yaml | 1 + .github/workflows/release.yaml | 1 + .github/workflows/testing.yaml | 50 +- pinecone/__init__.py | 4 +- pinecone/config/__init__.py | 6 + pinecone/config/logging.py | 8 - pinecone/control/index_host_store.py | 3 +- .../control/models/collection_description.py | 7 - pinecone/control/models/index_description.py | 13 - pinecone/control/pinecone.py | 150 +++-- pinecone/core/client/__init__.py | 7 +- pinecone/core/client/api/__init__.py | 2 +- ...tions_api.py => manage_pod_indexes_api.py} | 202 +++---- .../api/manage_serverless_indexes_api.py | 525 ++++++++++++++++++ .../core/client/api/vector_operations_api.py | 7 +- pinecone/core/client/api_client.py | 9 +- pinecone/core/client/apis/__init__.py | 5 +- pinecone/core/client/configuration.py | 27 +- pinecone/core/client/exceptions.py | 7 +- pinecone/core/client/model/aws_regions.py | 289 ++++++++++ ...line_response200.py => collection_list.py} | 25 +- ...collection_meta.py => collection_model.py} | 46 +- .../client/model/configure_index_request.py | 267 +++++++++ .../model/configure_index_request_spec.py | 267 +++++++++ ...py => configure_index_request_spec_pod.py} | 33 +- .../client/model/create_collection_request.py | 7 +- ...x_list_meta.py => create_index_request.py} | 65 +-- pinecone/core/client/model/create_request.py | 331 ----------- pinecone/core/client/model/delete_request.py | 7 +- .../model/describe_index_stats_request.py | 7 +- .../model/describe_index_stats_response.py | 7 +- .../{index_meta.py => error_response.py} | 41 +- .../core/client/model/error_response_error.py | 291 ++++++++++ pinecone/core/client/model/fetch_response.py | 7 +- pinecone/core/client/model/gcp_regions.py | 292 ++++++++++ pinecone/core/client/model/hnsw_config.py | 268 --------- pinecone/core/client/model/index_dimension.py | 288 ++++++++++ .../{approximated_config.py => index_list.py} | 31 +- .../core/client/model/index_meta_database.py | 310 ----------- pinecone/core/client/model/index_metric.py | 289 ++++++++++ pinecone/core/client/model/index_model.py | 297 ++++++++++ .../core/client/model/index_model_spec.py | 267 +++++++++ ...x_meta_status.py => index_model_status.py} | 29 +- .../core/client/model/namespace_summary.py | 7 +- pinecone/core/client/model/pod_spec.py | 296 ++++++++++ .../client/model/pod_spec_metadata_config.py | 255 +++++++++ .../core/client/model/pod_spec_pod_type.py | 290 ++++++++++ .../core/client/model/pod_spec_replicas.py | 287 ++++++++++ pinecone/core/client/model/pod_spec_shards.py | 287 ++++++++++ pinecone/core/client/model/protobuf_any.py | 7 +- .../core/client/model/protobuf_null_value.py | 7 +- pinecone/core/client/model/query_request.py | 7 +- pinecone/core/client/model/query_response.py | 7 +- pinecone/core/client/model/query_vector.py | 7 +- pinecone/core/client/model/rpc_status.py | 7 +- pinecone/core/client/model/scored_vector.py | 7 +- pinecone/core/client/model/serverless_spec.py | 272 +++++++++ .../core/client/model/single_query_results.py | 7 +- pinecone/core/client/model/sparse_values.py | 7 +- pinecone/core/client/model/update_request.py | 7 +- pinecone/core/client/model/upsert_request.py | 7 +- pinecone/core/client/model/upsert_response.py | 7 +- pinecone/core/client/model/vector.py | 7 +- pinecone/core/client/model_utils.py | 7 +- pinecone/core/client/models/__init__.py | 32 +- pinecone/core/client/rest.py | 44 +- pinecone/models/__init__.py | 12 + pinecone/models/collection_description.py | 5 + pinecone/models/index_description.py | 31 ++ tests/integration/__init__.py | 0 tests/integration/conftest.py | 80 +++ tests/integration/helpers/__init__.py | 0 tests/integration/helpers/helpers.py | 45 ++ tests/integration/test_collections.py | 39 ++ .../test_create_index_api_errors.py | 31 ++ .../test_create_index_happy_path.py | 18 + .../integration/test_create_index_timeouts.py | 28 + .../test_create_index_type_errors.py | 13 + tests/integration/test_describe_index.py | 30 + tests/integration/test_list_indexes.py | 23 + tests/unit/test_control.py | 4 +- 85 files changed, 5610 insertions(+), 1416 deletions(-) delete mode 100644 pinecone/config/logging.py delete mode 100644 pinecone/control/models/collection_description.py delete mode 100644 pinecone/control/models/index_description.py rename pinecone/core/client/api/{index_operations_api.py => manage_pod_indexes_api.py} (86%) create mode 100644 pinecone/core/client/api/manage_serverless_indexes_api.py create mode 100644 pinecone/core/client/model/aws_regions.py rename pinecone/core/client/model/{inline_response200.py => collection_list.py} (93%) rename pinecone/core/client/model/{collection_meta.py => collection_model.py} (87%) create mode 100644 pinecone/core/client/model/configure_index_request.py create mode 100644 pinecone/core/client/model/configure_index_request_spec.py rename pinecone/core/client/model/{patch_request.py => configure_index_request_spec_pod.py} (90%) rename pinecone/core/client/model/{index_list_meta.py => create_index_request.py} (84%) delete mode 100644 pinecone/core/client/model/create_request.py rename pinecone/core/client/model/{index_meta.py => error_response.py} (90%) create mode 100644 pinecone/core/client/model/error_response_error.py create mode 100644 pinecone/core/client/model/gcp_regions.py delete mode 100644 pinecone/core/client/model/hnsw_config.py create mode 100644 pinecone/core/client/model/index_dimension.py rename pinecone/core/client/model/{approximated_config.py => index_list.py} (91%) delete mode 100644 pinecone/core/client/model/index_meta_database.py create mode 100644 pinecone/core/client/model/index_metric.py create mode 100644 pinecone/core/client/model/index_model.py create mode 100644 pinecone/core/client/model/index_model_spec.py rename pinecone/core/client/model/{index_meta_status.py => index_model_status.py} (92%) create mode 100644 pinecone/core/client/model/pod_spec.py create mode 100644 pinecone/core/client/model/pod_spec_metadata_config.py create mode 100644 pinecone/core/client/model/pod_spec_pod_type.py create mode 100644 pinecone/core/client/model/pod_spec_replicas.py create mode 100644 pinecone/core/client/model/pod_spec_shards.py create mode 100644 pinecone/core/client/model/serverless_spec.py create mode 100644 pinecone/models/__init__.py create mode 100644 pinecone/models/collection_description.py create mode 100644 pinecone/models/index_description.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/conftest.py create mode 100644 tests/integration/helpers/__init__.py create mode 100644 tests/integration/helpers/helpers.py create mode 100644 tests/integration/test_collections.py create mode 100644 tests/integration/test_create_index_api_errors.py create mode 100644 tests/integration/test_create_index_happy_path.py create mode 100644 tests/integration/test_create_index_timeouts.py create mode 100644 tests/integration/test_create_index_type_errors.py create mode 100644 tests/integration/test_describe_index.py create mode 100644 tests/integration/test_list_indexes.py diff --git a/.github/workflows/alpha-release.yaml b/.github/workflows/alpha-release.yaml index 8ed480628..9c0c458c6 100644 --- a/.github/workflows/alpha-release.yaml +++ b/.github/workflows/alpha-release.yaml @@ -26,6 +26,7 @@ on: jobs: testing: uses: './.github/workflows/testing.yaml' + secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' diff --git a/.github/workflows/nightly-release.yaml b/.github/workflows/nightly-release.yaml index 25bf073af..1a18dbd78 100644 --- a/.github/workflows/nightly-release.yaml +++ b/.github/workflows/nightly-release.yaml @@ -8,6 +8,7 @@ on: jobs: run-tests: uses: './.github/workflows/testing.yaml' + secrets: inherit pypi-nightly: needs: run-tests diff --git a/.github/workflows/nightly-spruce-dev-release.yaml b/.github/workflows/nightly-spruce-dev-release.yaml index 2c494ca9b..be49ecf8d 100644 --- a/.github/workflows/nightly-spruce-dev-release.yaml +++ b/.github/workflows/nightly-spruce-dev-release.yaml @@ -8,6 +8,7 @@ on: jobs: run-tests: uses: './.github/workflows/testing.yaml' + secrets: inherit pypi-spruce-nightly: needs: run-tests diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index d61f74946..936952fdf 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -10,6 +10,7 @@ on: jobs: run-tests: uses: './.github/workflows/testing.yaml' + secrets: inherit build-docs: name: Build docs with pdoc diff --git a/.github/workflows/release-spruce.yaml b/.github/workflows/release-spruce.yaml index ca78a841f..178299ac1 100644 --- a/.github/workflows/release-spruce.yaml +++ b/.github/workflows/release-spruce.yaml @@ -6,6 +6,7 @@ on: jobs: testing: uses: './.github/workflows/testing.yaml' + secrets: inherit version-and-release-spruce: timeout-minutes: 30 diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index e7a12752c..be68a71ec 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -25,6 +25,7 @@ env: jobs: testing: uses: './.github/workflows/testing.yaml' + secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 678ad8760..9279cacb1 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -5,14 +5,14 @@ on: jobs: units-no-grpc: - name: Run tests (REST) + name: Unit tests (REST) runs-on: ubuntu-latest strategy: matrix: python-version: [3.8, 3.9, '3.10', 3.11] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 @@ -32,15 +32,55 @@ jobs: # so we don't add new regressions. poetry run mypy pinecone --exclude pinecone/core --exclude pinecone/grpc + integration-rest: + name: Integration tests (REST) + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8, 3.11] + pineconeEnv: ['prod', 'staging'] + max-parallel: 1 + fail-fast: false + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + + - name: Run integration tests (REST, prod) + if: matrix.pineconeEnv == 'prod' + run: poetry run pytest tests/integration -s -v + env: + PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} + TEST_CAPACITY_MODE_1: ${{ secrets.TEST_CAPACITY_MODE_1 }} + TEST_CAPACITY_MODE_2: ${{ secrets.TEST_CAPACITY_MODE_2 }} + GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.python-version}}" + + - name: Run integration tests (REST, staging) + if: matrix.pineconeEnv == 'staging' + run: poetry run pytest tests/integration -s -v + env: + PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY_STAGING }} + TEST_CAPACITY_MODE_1: ${{ secrets.TEST_CAPACITY_MODE_1 }} + TEST_CAPACITY_MODE_2: ${{ secrets.TEST_CAPACITY_MODE_2 }} + GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.python-version}}" + units-grpc: - name: Run tests (GRPC) + name: Unit tests (GRPC) runs-on: ubuntu-latest strategy: matrix: python-version: [3.8, 3.9, '3.10', 3.11] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 @@ -71,7 +111,7 @@ jobs: python-version: [3.8, 3.9, '3.10', 3.11] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 diff --git a/pinecone/__init__.py b/pinecone/__init__.py index fbacdaddd..fe52da72b 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -4,4 +4,6 @@ from .config import * from .exceptions import * from .control.pinecone import Pinecone -from .data.index import * \ No newline at end of file +from .data.index import * +from .models import * +from .core.client.models import * \ No newline at end of file diff --git a/pinecone/config/__init__.py b/pinecone/config/__init__.py index f6b039009..81d51fa02 100644 --- a/pinecone/config/__init__.py +++ b/pinecone/config/__init__.py @@ -1,2 +1,8 @@ +import logging +import os + from .config import ConfigBuilder, Config from .pinecone_config import PineconeConfig + +if (os.getenv('PINECONE_DEBUG') != None): + logging.basicConfig(level=logging.DEBUG) \ No newline at end of file diff --git a/pinecone/config/logging.py b/pinecone/config/logging.py deleted file mode 100644 index 51c788553..000000000 --- a/pinecone/config/logging.py +++ /dev/null @@ -1,8 +0,0 @@ -import logging - -PARENT_LOGGER_NAME = "pinecone" -DEFAULT_PARENT_LOGGER_LEVEL = "ERROR" - -_logger = logging.getLogger(__name__) -_parent_logger = logging.getLogger(PARENT_LOGGER_NAME) -_parent_logger.setLevel(DEFAULT_PARENT_LOGGER_LEVEL) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index dc15a0a92..38354ee18 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,7 +1,6 @@ from typing import Dict from pinecone.config import Config -from pinecone.core.client.api.index_operations_api import IndexOperationsApi - +from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi class SingletonMeta(type): _instances: Dict[str, str] = {} diff --git a/pinecone/control/models/collection_description.py b/pinecone/control/models/collection_description.py deleted file mode 100644 index ff3f4b41a..000000000 --- a/pinecone/control/models/collection_description.py +++ /dev/null @@ -1,7 +0,0 @@ -class CollectionDescription(object): - def __init__(self, keys, values): - for k, v in zip(keys, values): - self.__dict__[k] = v - - def __str__(self): - return str(self.__dict__) diff --git a/pinecone/control/models/index_description.py b/pinecone/control/models/index_description.py deleted file mode 100644 index e86ffbd59..000000000 --- a/pinecone/control/models/index_description.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import NamedTuple - - -class IndexDescription(NamedTuple): - name: str - metric: str - replicas: int - dimension: int - shards: int - pods: int - pod_type: str - status: None - metadata_config: None diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 7155b08d4..c2d83489f 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -1,20 +1,24 @@ import time -from typing import Optional, Dict, Any, cast +from typing import Optional, Dict, Any, Union, List, cast, NamedTuple from .index_host_store import IndexHostStore from pinecone.config import PineconeConfig, Config -from pinecone.control.models.index_description import IndexDescription -from pinecone.control.models.collection_description import CollectionDescription - -from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi from pinecone.core.client.api_client import ApiClient -from pinecone.core.client.models import CreateCollectionRequest, CreateRequest, PatchRequest from pinecone.utils import get_user_agent +from pinecone.core.client.models import ( + CreateCollectionRequest, + CreateIndexRequest, + ConfigureIndexRequest, + IndexMetric, + IndexDimension +) from pinecone.data import Index + class Pinecone: def __init__( self, @@ -32,7 +36,7 @@ def __init__( self.config = configKwarg else: self.config = PineconeConfig.build(api_key=api_key, host=host, **kwargs) - + if index_api: self.index_api = index_api else: @@ -42,24 +46,52 @@ def __init__( self.index_host_store = IndexHostStore() - def create_index( + def create_serverless_index( self, name: str, dimension: int, - cloud: str, region: str, - capacity_mode: str, - environment: Optional[str] = None, + cloud: str, + metric: Optional[str] = "cosine", + timeout: Optional[int] = None, + ): + spec = {'serverless': dict(region=region, cloud=cloud)} + self.create_index(name=name, dimension=dimension, metric=metric, spec=spec, timeout=timeout) + + def create_pod_index( + self, + name: str, + dimension: int, + environment: str, + metric: Optional[str] = "cosine", + replicas: Optional[int] = None, + shards: Optional[int] = None, + pods: Optional[int] = None, + pod_type: Optional[str] = "p1.x1", + metadata_config: Optional[Dict] = None, + source_collection: Optional[str] = None, + timeout: Optional[int] = None, + ): + spec_inner = dict( + environment=environment, + replicas=replicas, + shards=shards, + pods=pods, + pod_type=pod_type, + metadata_config=metadata_config, + source_collection=source_collection, + ) + filtered_spec_inner = {k: v for k, v in spec_inner.items() if v is not None} + spec = {'pod': filtered_spec_inner} + self.create_index(name=name, dimension=dimension, metric=metric, spec=spec, timeout=timeout) + + def create_index( + self, + name: str, + dimension: int, + spec: Dict, + metric: Optional[str] = "cosine", timeout: Optional[int] = None, - index_type: str = "approximated", - metric: str = "cosine", - replicas: int = 1, - shards: int = 1, - pods: int = 1, - pod_type: str = "p1", - index_config: Optional[dict] = {}, - metadata_config: Optional[dict] = None, - source_collection: str = "", ): """Creates a Pinecone index. @@ -67,51 +99,22 @@ def create_index( :type name: str :param dimension: the dimension of vectors that would be inserted in the index :type dimension: int - :param cloud: The cloud where you would like your index hosted. One of `{"aws", "gcp"}`. - :type cloud: str - :param region: The region where you would like your index hosted. - :type region: str - :param capacity_mode: The capacity mode for the index. One of `{"pod"}`. - :type capacity_mode: str - :param environment: The environment where you would like your index hosted, e.g. 'us-east1-gcp'. Find this value in the Pinecone web console along with your API keys. - :type environment: str, optional - :param index_type: type of index, one of `{"approximated", "exact"}`, defaults to "approximated". - The "approximated" index uses fast approximate search algorithms developed by Pinecone. - The "exact" index uses accurate exact search algorithms. - It performs exhaustive searches and thus it is usually slower than the "approximated" index. - :type index_type: str, optional :param metric: type of metric used in the vector index, one of `{"cosine", "dotproduct", "euclidean"}`, defaults to "cosine". Use "cosine" for cosine similarity, "dotproduct" for dot-product, and "euclidean" for euclidean distance. :type metric: str, optional - :param replicas: the number of replicas, defaults to 1. - Use at least 2 replicas if you need high availability (99.99% uptime) for querying. - For additional throughput (QPS) your index needs to support, provision additional replicas. - :type replicas: int, optional - :param shards: the number of shards per index, defaults to 1. - Use 1 shard per 1GB of vectors - :type shards: int,optional - :param pods: Total number of pods to be used by the index. pods = shard*replicas - :type pods: int,optional - :param pod_type: the pod type to be used for the index. can be one of p1 or s1. - :type pod_type: str,optional - :param index_config: Advanced configuration options for the index - :param metadata_config: Configuration related to the metadata index - :type metadata_config: dict, optional - :param source_collection: Collection name to create the index from - :type metadata_config: 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: Timeout for 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 """ - create_args = locals() - del create_args["self"] - if environment is None: - del create_args["environment"] api_instance = self.index_api - api_instance.create_index(create_request=CreateRequest(**create_args)) + + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec)) def is_ready(): status = self._get_status(name) @@ -173,8 +176,7 @@ def get_remaining(): def list_indexes(self): """Lists all indexes.""" - response = self.index_api.list_indexes() - return response + return self.index_api.list_indexes() def describe_index(self, name: str): """Describes a Pinecone index. @@ -183,25 +185,13 @@ def describe_index(self, name: str): :return: Returns an `IndexDescription` object """ api_instance = self.index_api - response = api_instance.describe_index(name) - db = response.database - host = response.status.host - + description = api_instance.describe_index(name) + host = description.host self.index_host_store.set_host(self.config, name, host) - return IndexDescription( - name=db.name, - metric=db.metric, - replicas=db.replicas, - dimension=db.dimension, - shards=db.shards, - pods=db.pods, - pod_type=db.pod_type, - status=response.status, - metadata_config=db.metadata_config, - ) + return description - def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: Optional[str] = ""): + def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: Optional[str] = None): """Changes current configuration of the index. :param: name: the name of the Index :param: replicas: the desired number of replicas, lowest value is 0. @@ -209,23 +199,23 @@ def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: O """ api_instance = self.index_api config_args: Dict[str, Any] = {} - if pod_type != "": + if pod_type: config_args.update(pod_type=pod_type) if replicas: config_args.update(replicas=replicas) - patch_request = PatchRequest(**config_args) - api_instance.configure_index(name, patch_request=patch_request) + configure_index_request = ConfigureIndexRequest(**config_args) + api_instance.configure_index(name, configure_index_request=configure_index_request) def scale_index(self, name: str, replicas: int): - """Increases number of replicas for the index. + """Change the number of replicas for the index. Replicas may be scaled up or down. :param name: the name of the Index :type name: str - :param replicas: the number of replicas in the index now, lowest value is 0. + :param replicas: the number of replicas in the index now, lowest value is 1. :type replicas: int """ api_instance = self.index_api - api_instance.configure_index(name, patch_request=PatchRequest(replicas=replicas, pod_type="")) + api_instance.configure_index(name, patch_request=ConfigureIndexRequest(replicas=replicas, pod_type="")) def create_collection(self, name: str, source: str): """Create a collection @@ -254,9 +244,7 @@ def describe_collection(self, name: str): :return: Description of the collection """ api_instance = self.index_api - response = api_instance.describe_collection(name).to_dict() - response_object = CollectionDescription(response.keys(), response.values()) - return response_object + return api_instance.describe_collection(name).to_dict() def _get_status(self, name: str): api_instance = self.index_api diff --git a/pinecone/core/client/__init__.py b/pinecone/core/client/__init__.py index 584d1219b..486f91455 100644 --- a/pinecone/core/client/__init__.py +++ b/pinecone/core/client/__init__.py @@ -1,12 +1,11 @@ # flake8: noqa """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/api/__init__.py b/pinecone/core/client/api/__init__.py index 14e304372..a4e950c74 100644 --- a/pinecone/core/client/api/__init__.py +++ b/pinecone/core/client/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.client.apis import IndexOperationsApi +# from pinecone.core.client.apis import ManagePodIndexesApi diff --git a/pinecone/core/client/api/index_operations_api.py b/pinecone/core/client/api/manage_pod_indexes_api.py similarity index 86% rename from pinecone/core/client/api/index_operations_api.py rename to pinecone/core/client/api/manage_pod_indexes_api.py index 0e31c7800..53bd97434 100644 --- a/pinecone/core/client/api/index_operations_api.py +++ b/pinecone/core/client/api/manage_pod_indexes_api.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -22,15 +21,17 @@ none_type, validate_and_convert_types ) -from pinecone.core.client.model.collection_meta import CollectionMeta +from pinecone.core.client.model.collection_list import CollectionList +from pinecone.core.client.model.collection_model import CollectionModel +from pinecone.core.client.model.configure_index_request import ConfigureIndexRequest from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_request import CreateRequest -from pinecone.core.client.model.index_meta import IndexMeta -from pinecone.core.client.model.inline_response200 import InlineResponse200 -from pinecone.core.client.model.patch_request import PatchRequest +from pinecone.core.client.model.create_index_request import CreateIndexRequest +from pinecone.core.client.model.error_response import ErrorResponse +from pinecone.core.client.model.index_list import IndexList +from pinecone.core.client.model.index_model import IndexModel -class IndexOperationsApi(object): +class ManagePodIndexesApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech @@ -45,6 +46,7 @@ def __init__(self, api_client=None): def __configure_index( self, index_name, + configure_index_request, **kwargs ): """configure_index # noqa: E501 @@ -53,14 +55,14 @@ def __configure_index( This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.configure_index(index_name, async_req=True) + >>> thread = api.configure_index(index_name, configure_index_request, async_req=True) >>> result = thread.get() Args: - index_name (str): The name of the index + index_name (str): The name of the index to configure + configure_index_request (ConfigureIndexRequest): The desired pod type and replica configuration for the index. Keyword Args: - patch_request (PatchRequest): The desired pod type and replica configuration for the index.. [optional] _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 @@ -82,7 +84,7 @@ def __configure_index( async_req (bool): execute request asynchronously Returns: - IndexMeta + IndexModel If the method is called asynchronously, returns the request thread. """ @@ -107,37 +109,34 @@ def __configure_index( kwargs['_host_index'] = kwargs.get('_host_index') kwargs['index_name'] = \ index_name + kwargs['configure_index_request'] = \ + configure_index_request return self.call_with_http_info(**kwargs) self.configure_index = _Endpoint( settings={ - 'response_type': (IndexMeta,), + 'response_type': (IndexModel,), 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/databases/{indexName}', + 'endpoint_path': '/indexes/{index_name}', 'operation_id': 'configure_index', 'http_method': 'PATCH', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, params_map={ 'all': [ 'index_name', - 'patch_request', + 'configure_index_request', ], 'required': [ 'index_name', + 'configure_index_request', ], 'nullable': [ ], @@ -154,15 +153,15 @@ def __configure_index( 'openapi_types': { 'index_name': (str,), - 'patch_request': - (PatchRequest,), + 'configure_index_request': + (ConfigureIndexRequest,), }, 'attribute_map': { - 'index_name': 'indexName', + 'index_name': 'index_name', }, 'location_map': { 'index_name': 'path', - 'patch_request': 'body', + 'configure_index_request': 'body', }, 'collection_format_map': { } @@ -181,6 +180,7 @@ def __configure_index( def __create_collection( self, + create_collection_request, **kwargs ): """create_collection # noqa: E501 @@ -189,12 +189,13 @@ def __create_collection( This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.create_collection(async_req=True) + >>> thread = api.create_collection(create_collection_request, async_req=True) >>> result = thread.get() + Args: + create_collection_request (CreateCollectionRequest): The desired configuration for the collection. Keyword Args: - create_collection_request (CreateCollectionRequest): [optional] _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 @@ -216,7 +217,7 @@ def __create_collection( async_req (bool): execute request asynchronously Returns: - str + CollectionModel If the method is called asynchronously, returns the request thread. """ @@ -239,11 +240,13 @@ def __create_collection( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['create_collection_request'] = \ + create_collection_request return self.call_with_http_info(**kwargs) self.create_collection = _Endpoint( settings={ - 'response_type': (str,), + 'response_type': (CollectionModel,), 'auth': [ 'ApiKeyAuth' ], @@ -254,12 +257,6 @@ def __create_collection( { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -267,7 +264,9 @@ def __create_collection( 'all': [ 'create_collection_request', ], - 'required': [], + 'required': [ + 'create_collection_request', + ], 'nullable': [ ], 'enum': [ @@ -294,7 +293,7 @@ def __create_collection( }, headers_map={ 'accept': [ - 'text/plain' + 'application/json' ], 'content_type': [ 'application/json' @@ -306,20 +305,22 @@ def __create_collection( def __create_index( self, + create_index_request, **kwargs ): """create_index # noqa: E501 - This operation creates a Pinecone index. You can use it to specify the measure of similarity, the dimension of vectors to be stored in the index, the numbers of shards and replicas to use, and more. # noqa: E501 + This operation deploys a Pinecone index. This is where you specify the measure of similarity, the dimension of vectors to be stored in the index, which cloud provider you would like to deploy with, and more. # 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(async_req=True) + >>> thread = api.create_index(create_index_request, async_req=True) >>> result = thread.get() + Args: + create_index_request (CreateIndexRequest): The desired configuration for the index. Keyword Args: - create_request (CreateRequest): [optional] _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 @@ -341,7 +342,7 @@ def __create_index( async_req (bool): execute request asynchronously Returns: - IndexMeta + IndexModel If the method is called asynchronously, returns the request thread. """ @@ -364,35 +365,33 @@ def __create_index( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['create_index_request'] = \ + create_index_request return self.call_with_http_info(**kwargs) self.create_index = _Endpoint( settings={ - 'response_type': (IndexMeta,), + 'response_type': (IndexModel,), 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/databases', + 'endpoint_path': '/indexes', 'operation_id': 'create_index', 'http_method': 'POST', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, params_map={ 'all': [ - 'create_request', + 'create_index_request', + ], + 'required': [ + 'create_index_request', ], - 'required': [], 'nullable': [ ], 'enum': [ @@ -406,13 +405,13 @@ def __create_index( 'allowed_values': { }, 'openapi_types': { - 'create_request': - (CreateRequest,), + 'create_index_request': + (CreateIndexRequest,), }, 'attribute_map': { }, 'location_map': { - 'create_request': 'body', + 'create_index_request': 'body', }, 'collection_format_map': { } @@ -501,19 +500,13 @@ def __delete_collection( 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/collections/{collectionName}', + 'endpoint_path': '/collections/{collection_name}', 'operation_id': 'delete_collection', 'http_method': 'DELETE', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -541,7 +534,7 @@ def __delete_collection( (str,), }, 'attribute_map': { - 'collection_name': 'collectionName', + 'collection_name': 'collection_name', }, 'location_map': { 'collection_name': 'path', @@ -551,7 +544,8 @@ def __delete_collection( }, headers_map={ 'accept': [ - 'text/plain' + 'text/plain', + 'application/json' ], 'content_type': [], }, @@ -574,7 +568,7 @@ def __delete_index( >>> result = thread.get() Args: - index_name (str): The name of the index + index_name (str): The name of the index to delete Keyword Args: _return_http_data_only (bool): response data without head status @@ -598,7 +592,7 @@ def __delete_index( async_req (bool): execute request asynchronously Returns: - str + None If the method is called asynchronously, returns the request thread. """ @@ -627,23 +621,17 @@ def __delete_index( self.delete_index = _Endpoint( settings={ - 'response_type': (str,), + 'response_type': None, 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/databases/{indexName}', + 'endpoint_path': '/indexes/{index_name}', 'operation_id': 'delete_index', 'http_method': 'DELETE', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -671,7 +659,7 @@ def __delete_index( (str,), }, 'attribute_map': { - 'index_name': 'indexName', + 'index_name': 'index_name', }, 'location_map': { 'index_name': 'path', @@ -681,7 +669,7 @@ def __delete_index( }, headers_map={ 'accept': [ - 'text/plain' + 'application/json' ], 'content_type': [], }, @@ -696,7 +684,7 @@ def __describe_collection( ): """describe_collection # noqa: E501 - Get a description of a collection. # noqa: E501 + This operation gets a description of a collection. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -704,7 +692,7 @@ def __describe_collection( >>> result = thread.get() Args: - collection_name (str): The name of the collection + collection_name (str): The name of the collection to be described Keyword Args: _return_http_data_only (bool): response data without head status @@ -728,7 +716,7 @@ def __describe_collection( async_req (bool): execute request asynchronously Returns: - CollectionMeta + CollectionModel If the method is called asynchronously, returns the request thread. """ @@ -757,23 +745,17 @@ def __describe_collection( self.describe_collection = _Endpoint( settings={ - 'response_type': (CollectionMeta,), + 'response_type': (CollectionModel,), 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/collections/{collectionName}', + 'endpoint_path': '/collections/{collection_name}', 'operation_id': 'describe_collection', 'http_method': 'GET', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -801,7 +783,7 @@ def __describe_collection( (str,), }, 'attribute_map': { - 'collection_name': 'collectionName', + 'collection_name': 'collection_name', }, 'location_map': { 'collection_name': 'path', @@ -834,7 +816,7 @@ def __describe_index( >>> result = thread.get() Args: - index_name (str): The name of the index + index_name (str): The name of the index to be described Keyword Args: _return_http_data_only (bool): response data without head status @@ -858,7 +840,7 @@ def __describe_index( async_req (bool): execute request asynchronously Returns: - IndexMeta + IndexModel If the method is called asynchronously, returns the request thread. """ @@ -887,23 +869,17 @@ def __describe_index( self.describe_index = _Endpoint( settings={ - 'response_type': (IndexMeta,), + 'response_type': (IndexModel,), 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/databases/{indexName}', + 'endpoint_path': '/indexes/{index_name}', 'operation_id': 'describe_index', 'http_method': 'GET', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -931,7 +907,7 @@ def __describe_index( (str,), }, 'attribute_map': { - 'index_name': 'indexName', + 'index_name': 'index_name', }, 'location_map': { 'index_name': 'path', @@ -985,7 +961,7 @@ def __list_collections( async_req (bool): execute request asynchronously Returns: - [str] + CollectionList If the method is called asynchronously, returns the request thread. """ @@ -1012,7 +988,7 @@ def __list_collections( self.list_collections = _Endpoint( settings={ - 'response_type': ([str],), + 'response_type': (CollectionList,), 'auth': [ 'ApiKeyAuth' ], @@ -1023,12 +999,6 @@ def __list_collections( { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -1059,7 +1029,7 @@ def __list_collections( }, headers_map={ 'accept': [ - 'application/json; charset=utf-8' + 'application/json' ], 'content_type': [], }, @@ -1103,7 +1073,7 @@ def __list_indexes( async_req (bool): execute request asynchronously Returns: - InlineResponse200 + IndexList If the method is called asynchronously, returns the request thread. """ @@ -1130,23 +1100,17 @@ def __list_indexes( self.list_indexes = _Endpoint( settings={ - 'response_type': (InlineResponse200,), + 'response_type': (IndexList,), 'auth': [ 'ApiKeyAuth' ], - 'endpoint_path': '/databases', + 'endpoint_path': '/indexes', 'operation_id': 'list_indexes', 'http_method': 'GET', 'servers': [ { 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } }, ] }, @@ -1177,7 +1141,7 @@ def __list_indexes( }, headers_map={ 'accept': [ - 'application/json; charset=utf-8' + 'application/json' ], 'content_type': [], }, diff --git a/pinecone/core/client/api/manage_serverless_indexes_api.py b/pinecone/core/client/api/manage_serverless_indexes_api.py new file mode 100644 index 000000000..33eefee7d --- /dev/null +++ b/pinecone/core/client/api/manage_serverless_indexes_api.py @@ -0,0 +1,525 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.client.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from pinecone.core.client.model.create_index_request import CreateIndexRequest +from pinecone.core.client.model.error_response import ErrorResponse +from pinecone.core.client.model.index_list import IndexList +from pinecone.core.client.model.index_model import IndexModel + + +class ManageServerlessIndexesApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __create_index( + self, + create_index_request, + **kwargs + ): + """create_index # noqa: E501 + + This operation deploys a Pinecone index. This is where you specify the measure of similarity, the dimension of vectors to be stored in the index, which cloud provider you would like to deploy with, and more. # 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(create_index_request, async_req=True) + >>> result = thread.get() + + Args: + create_index_request (CreateIndexRequest): The desired configuration for the index. + + 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_request'] = \ + create_index_request + return self.call_with_http_info(**kwargs) + + self.create_index = _Endpoint( + settings={ + 'response_type': (IndexModel,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/indexes', + 'operation_id': 'create_index', + 'http_method': 'POST', + 'servers': [ + { + 'url': "https://api.pinecone.io", + 'description': "No description provided", + }, + ] + }, + params_map={ + 'all': [ + 'create_index_request', + ], + 'required': [ + 'create_index_request', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'create_index_request': + (CreateIndexRequest,), + }, + 'attribute_map': { + }, + 'location_map': { + 'create_index_request': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__create_index + ) + + def __delete_index( + self, + index_name, + **kwargs + ): + """delete_index # noqa: E501 + + This operation deletes an existing index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_index(index_name, async_req=True) + >>> result = thread.get() + + Args: + index_name (str): The name of the index to delete + + 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['index_name'] = \ + index_name + return self.call_with_http_info(**kwargs) + + self.delete_index = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/indexes/{index_name}', + 'operation_id': 'delete_index', + 'http_method': 'DELETE', + 'servers': [ + { + 'url': "https://api.pinecone.io", + 'description': "No description provided", + }, + ] + }, + params_map={ + 'all': [ + 'index_name', + ], + 'required': [ + 'index_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'index_name': + (str,), + }, + 'attribute_map': { + 'index_name': 'index_name', + }, + 'location_map': { + 'index_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_index + ) + + def __describe_index( + self, + index_name, + **kwargs + ): + """describe_index # noqa: E501 + + Get a description of an index. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.describe_index(index_name, async_req=True) + >>> result = thread.get() + + Args: + index_name (str): The name of the index to be described + + 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['index_name'] = \ + index_name + return self.call_with_http_info(**kwargs) + + self.describe_index = _Endpoint( + settings={ + 'response_type': (IndexModel,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/indexes/{index_name}', + 'operation_id': 'describe_index', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://api.pinecone.io", + 'description': "No description provided", + }, + ] + }, + params_map={ + 'all': [ + 'index_name', + ], + 'required': [ + 'index_name', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'index_name': + (str,), + }, + 'attribute_map': { + 'index_name': 'index_name', + }, + 'location_map': { + 'index_name': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__describe_index + ) + + def __list_indexes( + self, + **kwargs + ): + """list_indexes # noqa: E501 + + This operation returns a list of your Pinecone indexes. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.list_indexes(async_req=True) + >>> result = thread.get() + + + 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: + IndexList + 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') + return self.call_with_http_info(**kwargs) + + self.list_indexes = _Endpoint( + settings={ + 'response_type': (IndexList,), + 'auth': [ + 'ApiKeyAuth' + ], + 'endpoint_path': '/indexes', + 'operation_id': 'list_indexes', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://api.pinecone.io", + 'description': "No description provided", + }, + ] + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__list_indexes + ) diff --git a/pinecone/core/client/api/vector_operations_api.py b/pinecone/core/client/api/vector_operations_api.py index c5bc02a2a..9c423051e 100644 --- a/pinecone/core/client/api/vector_operations_api.py +++ b/pinecone/core/client/api/vector_operations_api.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/api_client.py b/pinecone/core/client/api_client.py index 770fc07cd..88cb5182d 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/client/api_client.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -762,7 +761,7 @@ def __call__(self, *args, **kwargs): """ This method is invoked when endpoints are called Example: - api_instance = IndexOperationsApi() + api_instance = ManagePodIndexesApi() api_instance.configure_index # this is an instance of the class Endpoint api_instance.configure_index() # this invokes api_instance.configure_index.__call__() which then invokes the callable functions stored in that endpoint at diff --git a/pinecone/core/client/apis/__init__.py b/pinecone/core/client/apis/__init__.py index ec42b1a85..bc39a4d40 100644 --- a/pinecone/core/client/apis/__init__.py +++ b/pinecone/core/client/apis/__init__.py @@ -6,7 +6,7 @@ # raise a `RecursionError`. # In order to avoid this, import only the API that you directly need like: # -# from .api.index_operations_api import IndexOperationsApi +# from .api.manage_pod_indexes_api import ManagePodIndexesApi # # or import this package, but before doing it, use: # @@ -14,5 +14,6 @@ # sys.setrecursionlimit(n) # Import APIs into API package: -from pinecone.core.client.api.index_operations_api import IndexOperationsApi +from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi +from pinecone.core.client.api.manage_serverless_indexes_api import ManageServerlessIndexesApi from pinecone.core.client.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/client/configuration.py b/pinecone/core/client/configuration.py index 6e2d4949b..99447c9f2 100644 --- a/pinecone/core/client/configuration.py +++ b/pinecone/core/client/configuration.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -113,7 +112,7 @@ def __init__(self, host=None, ): """Constructor """ - self._base_path = "https://unknown-unknown.svc.unknown.pinecone.io" if host is None else host + self._base_path = "https://api.pinecone.io" if host is None else host """Default Base url """ self.server_index = 0 if server_index is None and host is None else server_index @@ -406,7 +405,7 @@ def to_debug_report(self): return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ - "Version of the API: version not set\n"\ + "Version of the API: 1.0\n"\ "SDK Package Version: 1.0.0".\ format(env=sys.platform, pyversion=sys.version) @@ -417,22 +416,8 @@ def get_host_settings(self): """ return [ { - 'url': "https://{index_name}-{project_name}.svc.{environment}.pinecone.io", + 'url': "https://api.pinecone.io", 'description': "No description provided", - 'variables': { - 'index_name': { - 'description': "No description provided", - 'default_value': "unknown", - }, - 'project_name': { - 'description': "No description provided", - 'default_value': "unknown", - }, - 'environment': { - 'description': "No description provided", - 'default_value': "unknown", - } - } } ] diff --git a/pinecone/core/client/exceptions.py b/pinecone/core/client/exceptions.py index dd777d024..3d1ff935a 100644 --- a/pinecone/core/client/exceptions.py +++ b/pinecone/core/client/exceptions.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/aws_regions.py b/pinecone/core/client/model/aws_regions.py new file mode 100644 index 000000000..04848cb3f --- /dev/null +++ b/pinecone/core/client/model/aws_regions.py @@ -0,0 +1,289 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class AwsRegions(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'EAST-1': "us-east-1", + 'WEST-1': "us-west-1", + 'WEST-2': "us-west-2", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """AwsRegions - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Regions available with the AWS cloud provider., must be one of ["us-east-1", "us-west-1", "us-west-2", ] # noqa: E501 + + Keyword Args: + value (str): Regions available with the AWS cloud provider., must be one of ["us-east-1", "us-west-1", "us-west-2", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """AwsRegions - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Regions available with the AWS cloud provider., must be one of ["us-east-1", "us-west-1", "us-west-2", ] # noqa: E501 + + Keyword Args: + value (str): Regions available with the AWS cloud provider., must be one of ["us-east-1", "us-west-1", "us-west-2", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/inline_response200.py b/pinecone/core/client/model/collection_list.py similarity index 93% rename from pinecone/core/client/model/inline_response200.py rename to pinecone/core/client/model/collection_list.py index c7e991067..2cac53b57 100644 --- a/pinecone/core/client/model/inline_response200.py +++ b/pinecone/core/client/model/collection_list.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -31,11 +30,11 @@ def lazy_import(): - from pinecone.core.client.model.index_list_meta import IndexListMeta - globals()['IndexListMeta'] = IndexListMeta + from pinecone.core.client.model.collection_model import CollectionModel + globals()['CollectionModel'] = CollectionModel -class InlineResponse200(ModelNormal): +class CollectionList(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -88,7 +87,7 @@ def openapi_types(): """ lazy_import() return { - 'databases': ([IndexListMeta],), # noqa: E501 + 'collections': ([CollectionModel],), # noqa: E501 } @cached_property @@ -97,7 +96,7 @@ def discriminator(): attribute_map = { - 'databases': 'databases', # noqa: E501 + 'collections': 'collections', # noqa: E501 } read_only_vars = { @@ -108,7 +107,7 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """InlineResponse200 - a model defined in OpenAPI + """CollectionList - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -141,7 +140,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,) - databases ([IndexListMeta]): [optional] # noqa: E501 + collections ([CollectionModel]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -190,7 +189,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 - """InlineResponse200 - a model defined in OpenAPI + """CollectionList - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -223,7 +222,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,) - databases ([IndexListMeta]): [optional] # noqa: E501 + collections ([CollectionModel]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/collection_meta.py b/pinecone/core/client/model/collection_model.py similarity index 87% rename from pinecone/core/client/model/collection_meta.py rename to pinecone/core/client/model/collection_model.py index 9f33d5ef0..acbcaf952 100644 --- a/pinecone/core/client/model/collection_meta.py +++ b/pinecone/core/client/model/collection_model.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -31,7 +30,7 @@ -class CollectionMeta(ModelNormal): +class CollectionModel(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -56,9 +55,18 @@ class CollectionMeta(ModelNormal): """ allowed_values = { + ('status',): { + 'INITIALIZING': "Initializing", + 'READY': "Ready", + 'TERMINATING': "Terminating", + }, } validations = { + ('dimension',): { + 'inclusive_maximum': 2000, + 'inclusive_minimum': 1, + }, } @cached_property @@ -86,7 +94,8 @@ def openapi_types(): 'size': (int,), # noqa: E501 'status': (str,), # noqa: E501 'dimension': (int,), # noqa: E501 - 'vector_count': (int,), # noqa: E501 + 'record_count': (int,), # noqa: E501 + 'environment': (str,), # noqa: E501 } @cached_property @@ -99,7 +108,8 @@ def discriminator(): 'size': 'size', # noqa: E501 'status': 'status', # noqa: E501 'dimension': 'dimension', # noqa: E501 - 'vector_count': 'vector_count', # noqa: E501 + 'record_count': 'record_count', # noqa: E501 + 'environment': 'environment', # noqa: E501 } read_only_vars = { @@ -109,15 +119,15 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, size, status, dimension, vector_count, *args, **kwargs): # noqa: E501 - """CollectionMeta - a model defined in OpenAPI + def _from_openapi_data(cls, name, size, status, dimension, record_count, *args, **kwargs): # noqa: E501 + """CollectionModel - a model defined in OpenAPI Args: name (str): size (int): The size of the collection in bytes. status (str): The status of the collection. - dimension (int): The dimension of the records stored in the collection - vector_count (int): The number of records stored in the collection + dimension (int): The dimension of the vectors stored in each record held in the collection + record_count (int): The number of records stored in the collection Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -150,6 +160,7 @@ def _from_openapi_data(cls, name, size, status, dimension, vector_count, *args, Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + environment (str): The environment where the collection is hosted.. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -181,7 +192,7 @@ def _from_openapi_data(cls, name, size, status, dimension, vector_count, *args, self.size = size self.status = status self.dimension = dimension - self.vector_count = vector_count + self.record_count = record_count for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -202,15 +213,15 @@ def _from_openapi_data(cls, name, size, status, dimension, vector_count, *args, ]) @convert_js_args_to_python_args - def __init__(self, name, size, status, dimension, vector_count, *args, **kwargs): # noqa: E501 - """CollectionMeta - a model defined in OpenAPI + def __init__(self, name, size, status, dimension, record_count, *args, **kwargs): # noqa: E501 + """CollectionModel - a model defined in OpenAPI Args: name (str): size (int): The size of the collection in bytes. status (str): The status of the collection. - dimension (int): The dimension of the records stored in the collection - vector_count (int): The number of records stored in the collection + dimension (int): The dimension of the vectors stored in each record held in the collection + record_count (int): The number of records stored in the collection Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -243,6 +254,7 @@ def __init__(self, name, size, status, dimension, vector_count, *args, **kwargs) Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + environment (str): The environment where the collection is hosted.. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -272,7 +284,7 @@ def __init__(self, name, size, status, dimension, vector_count, *args, **kwargs) self.size = size self.status = status self.dimension = dimension - self.vector_count = vector_count + self.record_count = record_count for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/configure_index_request.py b/pinecone/core/client/model/configure_index_request.py new file mode 100644 index 000000000..864c1427b --- /dev/null +++ b/pinecone/core/client/model/configure_index_request.py @@ -0,0 +1,267 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.configure_index_request_spec import ConfigureIndexRequestSpec + globals()['ConfigureIndexRequestSpec'] = ConfigureIndexRequestSpec + + +class ConfigureIndexRequest(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'spec': (ConfigureIndexRequestSpec,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'spec': 'spec', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 + """ConfigureIndexRequest - a model defined in OpenAPI + + Args: + spec (ConfigureIndexRequestSpec): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + 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 ApiTypeError( + "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.spec = spec + 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, spec, *args, **kwargs): # noqa: E501 + """ConfigureIndexRequest - a model defined in OpenAPI + + Args: + spec (ConfigureIndexRequestSpec): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + 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 ApiTypeError( + "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.spec = spec + 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 ApiAttributeError(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/client/model/configure_index_request_spec.py b/pinecone/core/client/model/configure_index_request_spec.py new file mode 100644 index 000000000..e673d077f --- /dev/null +++ b/pinecone/core/client/model/configure_index_request_spec.py @@ -0,0 +1,267 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod + globals()['ConfigureIndexRequestSpecPod'] = ConfigureIndexRequestSpecPod + + +class ConfigureIndexRequestSpec(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pod': (ConfigureIndexRequestSpecPod,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'pod': 'pod', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pod, *args, **kwargs): # noqa: E501 + """ConfigureIndexRequestSpec - a model defined in OpenAPI + + Args: + pod (ConfigureIndexRequestSpecPod): + + 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 ApiTypeError( + "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.pod = pod + 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, pod, *args, **kwargs): # noqa: E501 + """ConfigureIndexRequestSpec - a model defined in OpenAPI + + Args: + pod (ConfigureIndexRequestSpecPod): + + 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 ApiTypeError( + "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.pod = pod + 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 ApiAttributeError(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/client/model/patch_request.py b/pinecone/core/client/model/configure_index_request_spec_pod.py similarity index 90% rename from pinecone/core/client/model/patch_request.py rename to pinecone/core/client/model/configure_index_request_spec_pod.py index 53425c222..fbfde79c1 100644 --- a/pinecone/core/client/model/patch_request.py +++ b/pinecone/core/client/model/configure_index_request_spec_pod.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -30,8 +29,14 @@ from pinecone.core.client.exceptions import ApiAttributeError +def lazy_import(): + from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType + from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas + globals()['PodSpecPodType'] = PodSpecPodType + globals()['PodSpecReplicas'] = PodSpecReplicas -class PatchRequest(ModelNormal): + +class ConfigureIndexRequestSpecPod(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -67,6 +72,7 @@ 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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -81,9 +87,10 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { - 'replicas': (int,), # noqa: E501 - 'pod_type': (str,), # noqa: E501 + 'replicas': (PodSpecReplicas,), # noqa: E501 + 'pod_type': (PodSpecPodType,), # noqa: E501 } @cached_property @@ -104,7 +111,7 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """PatchRequest - a model defined in OpenAPI + """ConfigureIndexRequestSpecPod - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -137,8 +144,8 @@ 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,) - replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 - pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] # noqa: E501 + replicas (PodSpecReplicas): [optional] # noqa: E501 + pod_type (PodSpecPodType): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -187,7 +194,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 - """PatchRequest - a model defined in OpenAPI + """ConfigureIndexRequestSpecPod - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -220,8 +227,8 @@ 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,) - replicas (int): The desired number of replicas for the index.. [optional] # noqa: E501 - pod_type (str): The new pod type for the index. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] # noqa: E501 + replicas (PodSpecReplicas): [optional] # noqa: E501 + pod_type (PodSpecPodType): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/create_collection_request.py b/pinecone/core/client/model/create_collection_request.py index 6cf24b7a7..c80103ae1 100644 --- a/pinecone/core/client/model/create_collection_request.py +++ b/pinecone/core/client/model/create_collection_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/index_list_meta.py b/pinecone/core/client/model/create_index_request.py similarity index 84% rename from pinecone/core/client/model/index_list_meta.py rename to pinecone/core/client/model/create_index_request.py index 7cfbd92d9..d0fd33ce3 100644 --- a/pinecone/core/client/model/index_list_meta.py +++ b/pinecone/core/client/model/create_index_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -30,8 +29,14 @@ from pinecone.core.client.exceptions import ApiAttributeError +def lazy_import(): + from pinecone.core.client.model.index_dimension import IndexDimension + from pinecone.core.client.model.index_metric import IndexMetric + globals()['IndexDimension'] = IndexDimension + globals()['IndexMetric'] = IndexMetric -class IndexListMeta(ModelNormal): + +class CreateIndexRequest(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -67,6 +72,7 @@ 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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -81,12 +87,12 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { 'name': (str,), # noqa: E501 - 'metric': (str,), # noqa: E501 - 'dimension': (int,), # noqa: E501 - 'capacity_mode': (str,), # noqa: E501 - 'host': (str,), # noqa: E501 + 'dimension': (IndexDimension,), # noqa: E501 + 'metric': (IndexMetric,), # noqa: E501 + 'spec': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 } @cached_property @@ -96,10 +102,9 @@ def discriminator(): attribute_map = { 'name': 'name', # noqa: E501 - 'metric': 'metric', # noqa: E501 'dimension': 'dimension', # noqa: E501 - 'capacity_mode': 'capacity_mode', # noqa: E501 - 'host': 'host', # noqa: E501 + 'metric': 'metric', # noqa: E501 + 'spec': 'spec', # noqa: E501 } read_only_vars = { @@ -109,15 +114,14 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, metric, dimension, capacity_mode, host, *args, **kwargs): # noqa: E501 - """IndexListMeta - a model defined in OpenAPI + def _from_openapi_data(cls, name, dimension, metric, spec, *args, **kwargs): # noqa: E501 + """CreateIndexRequest - a model defined in OpenAPI Args: - name (str): - metric (str): - dimension (int): - capacity_mode (str): - host (str): + name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. + dimension (IndexDimension): + metric (IndexMetric): + spec ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Spec objects describe how the index should be deployed Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -178,10 +182,9 @@ def _from_openapi_data(cls, name, metric, dimension, capacity_mode, host, *args, self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.metric = metric self.dimension = dimension - self.capacity_mode = capacity_mode - self.host = host + self.metric = metric + self.spec = spec for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -202,15 +205,14 @@ def _from_openapi_data(cls, name, metric, dimension, capacity_mode, host, *args, ]) @convert_js_args_to_python_args - def __init__(self, name, metric, dimension, capacity_mode, host, *args, **kwargs): # noqa: E501 - """IndexListMeta - a model defined in OpenAPI + def __init__(self, name, dimension, metric, spec, *args, **kwargs): # noqa: E501 + """CreateIndexRequest - a model defined in OpenAPI Args: - name (str): - metric (str): - dimension (int): - capacity_mode (str): - host (str): + name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. + dimension (IndexDimension): + metric (IndexMetric): + spec ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Spec objects describe how the index should be deployed Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -269,10 +271,9 @@ def __init__(self, name, metric, dimension, capacity_mode, host, *args, **kwargs self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.name = name - self.metric = metric self.dimension = dimension - self.capacity_mode = capacity_mode - self.host = host + self.metric = metric + self.spec = spec for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/create_request.py b/pinecone/core/client/model/create_request.py deleted file mode 100644 index e19d8d9e4..000000000 --- a/pinecone/core/client/model/create_request.py +++ /dev/null @@ -1,331 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class CreateRequest(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 = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'name': (str,), # noqa: E501 - 'dimension': (int,), # noqa: E501 - 'region': (str,), # noqa: E501 - 'cloud': (str,), # noqa: E501 - 'capacity_mode': (str,), # noqa: E501 - 'environment': (str,), # noqa: E501 - 'index_type': (str,), # noqa: E501 - 'metric': (str,), # noqa: E501 - 'pods': (int,), # noqa: E501 - 'replicas': (int,), # noqa: E501 - 'shards': (int,), # noqa: E501 - 'pod_type': (str,), # noqa: E501 - 'index_config': (dict,), # noqa: E501 - 'metadata_config': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 - 'source_collection': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'name': 'name', # noqa: E501 - 'dimension': 'dimension', # noqa: E501 - 'region': 'region', # noqa: E501 - 'cloud': 'cloud', # noqa: E501 - 'capacity_mode': 'capacity_mode', # noqa: E501 - 'environment': 'environment', # noqa: E501 - 'index_type': 'index_type', # noqa: E501 - 'metric': 'metric', # noqa: E501 - 'pods': 'pods', # noqa: E501 - 'replicas': 'replicas', # noqa: E501 - 'shards': 'shards', # noqa: E501 - 'pod_type': 'pod_type', # noqa: E501 - 'index_config': 'index_config', # noqa: E501 - 'metadata_config': 'metadata_config', # noqa: E501 - 'source_collection': 'source_collection', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, region, cloud, capacity_mode, *args, **kwargs): # noqa: E501 - """CreateRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index to be created. The maximum length is 45 characters. - dimension (int): The dimensions of the vectors to be inserted in the index - region (str): The region where you would like your index to be created - cloud (str): The public cloud where you would like your index hosted - capacity_mode (str): The capacity mode for 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,) - environment (str): The environment where you would like your index to be created. [optional] # noqa: E501 - index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 - 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 - pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 - source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( - "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.dimension = dimension - self.region = region - self.cloud = cloud - self.capacity_mode = capacity_mode - 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, dimension, region, cloud, capacity_mode, *args, **kwargs): # noqa: E501 - """CreateRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index to be created. The maximum length is 45 characters. - dimension (int): The dimensions of the vectors to be inserted in the index - region (str): The region where you would like your index to be created - cloud (str): The public cloud where you would like your index hosted - capacity_mode (str): The capacity mode for 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,) - environment (str): The environment where you would like your index to be created. [optional] # noqa: E501 - index_type (str): The type of vector index. Pinecone supports 'approximated'.. [optional] if omitted the server will use the default value of "approximated" # noqa: E501 - 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 - pods (int): The number of pods for the index to use,including replicas.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards to be used in the index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): Configuration for the behavior of Pinecone's internal metadata index. By default, all metadata is indexed; when `metadata_config` is present, only specified metadata fields are indexed. To specify metadata fields to index, provide a JSON object of the following form: ``` {\"indexed\": [\"example_metadata_field\"]} ``` . [optional] # noqa: E501 - source_collection (str): The name of the collection to create an index from. [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 ApiTypeError( - "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.dimension = dimension - self.region = region - self.cloud = cloud - self.capacity_mode = capacity_mode - 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 ApiAttributeError(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/client/model/delete_request.py b/pinecone/core/client/model/delete_request.py index 446466d57..10e0832b3 100644 --- a/pinecone/core/client/model/delete_request.py +++ b/pinecone/core/client/model/delete_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/describe_index_stats_request.py b/pinecone/core/client/model/describe_index_stats_request.py index da0eb0b24..a6f8de18d 100644 --- a/pinecone/core/client/model/describe_index_stats_request.py +++ b/pinecone/core/client/model/describe_index_stats_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/describe_index_stats_response.py b/pinecone/core/client/model/describe_index_stats_response.py index 9dc9c4056..e56c1ab87 100644 --- a/pinecone/core/client/model/describe_index_stats_response.py +++ b/pinecone/core/client/model/describe_index_stats_response.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/index_meta.py b/pinecone/core/client/model/error_response.py similarity index 90% rename from pinecone/core/client/model/index_meta.py rename to pinecone/core/client/model/error_response.py index baac4d5c4..543305804 100644 --- a/pinecone/core/client/model/index_meta.py +++ b/pinecone/core/client/model/error_response.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -31,13 +30,11 @@ def lazy_import(): - from pinecone.core.client.model.index_meta_database import IndexMetaDatabase - from pinecone.core.client.model.index_meta_status import IndexMetaStatus - globals()['IndexMetaDatabase'] = IndexMetaDatabase - globals()['IndexMetaStatus'] = IndexMetaStatus + from pinecone.core.client.model.error_response_error import ErrorResponseError + globals()['ErrorResponseError'] = ErrorResponseError -class IndexMeta(ModelNormal): +class ErrorResponse(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -90,8 +87,8 @@ def openapi_types(): """ lazy_import() return { - 'database': (IndexMetaDatabase,), # noqa: E501 - 'status': (IndexMetaStatus,), # noqa: E501 + 'status': (int,), # noqa: E501 + 'error': (ErrorResponseError,), # noqa: E501 } @cached_property @@ -100,8 +97,8 @@ def discriminator(): attribute_map = { - 'database': 'database', # noqa: E501 'status': 'status', # noqa: E501 + 'error': 'error', # noqa: E501 } read_only_vars = { @@ -111,12 +108,12 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, database, status, *args, **kwargs): # noqa: E501 - """IndexMeta - a model defined in OpenAPI + def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 + """ErrorResponse - a model defined in OpenAPI Args: - database (IndexMetaDatabase): - status (IndexMetaStatus): + status (int): The HTTP status code of the error + error (ErrorResponseError): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -176,8 +173,8 @@ def _from_openapi_data(cls, database, status, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.database = database self.status = status + self.error = error for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -198,12 +195,12 @@ def _from_openapi_data(cls, database, status, *args, **kwargs): # noqa: E501 ]) @convert_js_args_to_python_args - def __init__(self, database, status, *args, **kwargs): # noqa: E501 - """IndexMeta - a model defined in OpenAPI + def __init__(self, status, error, *args, **kwargs): # noqa: E501 + """ErrorResponse - a model defined in OpenAPI Args: - database (IndexMetaDatabase): - status (IndexMetaStatus): + status (int): The HTTP status code of the error + error (ErrorResponseError): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -261,8 +258,8 @@ def __init__(self, database, status, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.database = database self.status = status + self.error = error for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/error_response_error.py b/pinecone/core/client/model/error_response_error.py new file mode 100644 index 000000000..4edd409ff --- /dev/null +++ b/pinecone/core/client/model/error_response_error.py @@ -0,0 +1,291 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class ErrorResponseError(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 = { + ('code',): { + 'QUOTA_EXCEEDED': "QUOTA_EXCEEDED", + 'BAD_PARAMS': "BAD_PARAMS", + 'CANCELLED': "CANCELLED", + 'UNKNOWN': "UNKNOWN", + 'INVALID_ARGUMENT': "INVALID_ARGUMENT", + 'DEADLINE_EXCEEDED': "DEADLINE_EXCEEDED", + 'NOT_FOUND': "NOT_FOUND", + 'ALREADY_EXISTS': "ALREADY_EXISTS", + 'PERMISSION_DENIED': "PERMISSION_DENIED", + 'UNAUTHENTICATED': "UNAUTHENTICATED", + 'RESOURCE_EXHAUSTED': "RESOURCE_EXHAUSTED", + 'FAILED_PRECONDITION': "FAILED_PRECONDITION", + 'ABORTED': "ABORTED", + 'OUT_OF_RANGE': "OUT_OF_RANGE", + 'UNIMPLEMENTED': "UNIMPLEMENTED", + 'INTERNAL': "INTERNAL", + 'UNAVAILABLE': "UNAVAILABLE", + 'DATA_LOSS': "DATA_LOSS", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'code': (str,), # noqa: E501 + 'message': (str,), # noqa: E501 + 'details': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'code': 'code', # noqa: E501 + 'message': 'message', # noqa: E501 + 'details': 'details', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 + """ErrorResponseError - a model defined in OpenAPI + + Args: + code (str): + message (str): + + 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,) + details ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Additional information about the error. This field is not guaranteed to be present.. [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 ApiTypeError( + "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.code = code + self.message = message + 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, code, message, *args, **kwargs): # noqa: E501 + """ErrorResponseError - a model defined in OpenAPI + + Args: + code (str): + message (str): + + 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,) + details ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Additional information about the error. This field is not guaranteed to be present.. [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 ApiTypeError( + "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.code = code + self.message = message + 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 ApiAttributeError(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/client/model/fetch_response.py b/pinecone/core/client/model/fetch_response.py index d355980fc..64d0f1ab6 100644 --- a/pinecone/core/client/model/fetch_response.py +++ b/pinecone/core/client/model/fetch_response.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/gcp_regions.py b/pinecone/core/client/model/gcp_regions.py new file mode 100644 index 000000000..8ed733971 --- /dev/null +++ b/pinecone/core/client/model/gcp_regions.py @@ -0,0 +1,292 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class GcpRegions(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'US-WEST1': "us-west1", + 'US-WEST2': "us-west2", + 'EU-WEST4': "eu-west4", + 'NORTHAMERICA-NORTHEAST1': "northamerica-northeast1", + 'ASIA-NORTHEAST1': "asia-northeast1", + 'ASIA-SOUTHEAST1C': "asia-southeast1C", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """GcpRegions - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Regions available with the GCP cloud provider., must be one of ["us-west1", "us-west2", "eu-west4", "northamerica-northeast1", "asia-northeast1", "asia-southeast1C", ] # noqa: E501 + + Keyword Args: + value (str): Regions available with the GCP cloud provider., must be one of ["us-west1", "us-west2", "eu-west4", "northamerica-northeast1", "asia-northeast1", "asia-southeast1C", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """GcpRegions - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Regions available with the GCP cloud provider., must be one of ["us-west1", "us-west2", "eu-west4", "northamerica-northeast1", "asia-northeast1", "asia-southeast1C", ] # noqa: E501 + + Keyword Args: + value (str): Regions available with the GCP cloud provider., must be one of ["us-west1", "us-west2", "eu-west4", "northamerica-northeast1", "asia-northeast1", "asia-southeast1C", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/hnsw_config.py b/pinecone/core/client/model/hnsw_config.py deleted file mode 100644 index d6a99a345..000000000 --- a/pinecone/core/client/model/hnsw_config.py +++ /dev/null @@ -1,268 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class HnswConfig(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'ef_construction': (int,), # noqa: E501 - 'ef': (int,), # noqa: E501 - 'm': (int,), # noqa: E501 - 'max_elements': (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'ef_construction': 'ef_construction', # noqa: E501 - 'ef': 'ef', # noqa: E501 - 'm': 'M', # noqa: E501 - 'max_elements': 'max_elements', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """HnswConfig - 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,) - ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 - ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 - m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 - max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( - "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 - """HnswConfig - 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,) - ef_construction (int): [optional] if omitted the server will use the default value of 500 # noqa: E501 - ef (int): [optional] if omitted the server will use the default value of 250 # noqa: E501 - m (int): [optional] if omitted the server will use the default value of 12 # noqa: E501 - max_elements (int): [optional] if omitted the server will use the default value of 50000000 # 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 ApiTypeError( - "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 ApiAttributeError(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/client/model/index_dimension.py b/pinecone/core/client/model/index_dimension.py new file mode 100644 index 000000000..d6372eb12 --- /dev/null +++ b/pinecone/core/client/model/index_dimension.py @@ -0,0 +1,288 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class IndexDimension(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',): { + '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @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): + """IndexDimension - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The dimensions of the vectors to be inserted in the index. # noqa: E501 + + Keyword Args: + value (int): The dimensions of the vectors to be inserted in the index. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """IndexDimension - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The dimensions of the vectors to be inserted in the index. # noqa: E501 + + Keyword Args: + value (int): The dimensions of the vectors to be inserted in the index. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/approximated_config.py b/pinecone/core/client/model/index_list.py similarity index 91% rename from pinecone/core/client/model/approximated_config.py rename to pinecone/core/client/model/index_list.py index 9e881a945..a75628d53 100644 --- a/pinecone/core/client/model/approximated_config.py +++ b/pinecone/core/client/model/index_list.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -30,8 +29,12 @@ from pinecone.core.client.exceptions import ApiAttributeError +def lazy_import(): + from pinecone.core.client.model.index_model import IndexModel + globals()['IndexModel'] = IndexModel -class ApproximatedConfig(ModelNormal): + +class IndexList(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -67,6 +70,7 @@ 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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -81,9 +85,9 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { - 'k_bits': (int,), # noqa: E501 - 'hybrid': (bool,), # noqa: E501 + 'indexes': ([IndexModel],), # noqa: E501 } @cached_property @@ -92,8 +96,7 @@ def discriminator(): attribute_map = { - 'k_bits': 'k_bits', # noqa: E501 - 'hybrid': 'hybrid', # noqa: E501 + 'indexes': 'indexes', # noqa: E501 } read_only_vars = { @@ -104,7 +107,7 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ApproximatedConfig - a model defined in OpenAPI + """IndexList - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -137,8 +140,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,) - k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 - hybrid (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + indexes ([IndexModel]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -187,7 +189,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 - """ApproximatedConfig - a model defined in OpenAPI + """IndexList - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -220,8 +222,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,) - k_bits (int): [optional] if omitted the server will use the default value of 512 # noqa: E501 - hybrid (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + indexes ([IndexModel]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/index_meta_database.py b/pinecone/core/client/model/index_meta_database.py deleted file mode 100644 index 22c9381f7..000000000 --- a/pinecone/core/client/model/index_meta_database.py +++ /dev/null @@ -1,310 +0,0 @@ -""" - Pinecone API - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: version not set - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class IndexMetaDatabase(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'name': (str,), # noqa: E501 - 'dimension': (int,), # noqa: E501 - 'capacity_mode': (str,), # noqa: E501 - 'metric': (str,), # noqa: E501 - 'index_type': (str,), # noqa: E501 - 'pods': (int,), # noqa: E501 - 'replicas': (int,), # noqa: E501 - 'shards': (int,), # noqa: E501 - 'pod_type': (str,), # noqa: E501 - 'index_config': (dict,), # noqa: E501 - 'metadata_config': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'name': 'name', # noqa: E501 - 'dimension': 'dimension', # noqa: E501 - 'capacity_mode': 'capacity_mode', # noqa: E501 - 'metric': 'metric', # noqa: E501 - 'index_type': 'index_type', # noqa: E501 - 'pods': 'pods', # noqa: E501 - 'replicas': 'replicas', # noqa: E501 - 'shards': 'shards', # noqa: E501 - 'pod_type': 'pod_type', # noqa: E501 - 'index_config': 'index_config', # noqa: E501 - 'metadata_config': 'metadata_config', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, capacity_mode, *args, **kwargs): # noqa: E501 - """IndexMetaDatabase - a model defined in OpenAPI - - Args: - name (str): - dimension (int): - capacity_mode (str): - - Keyword Args: - metric (str): defaults to "cosine" # 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,) - index_type (str): [optional] # noqa: E501 - pods (int): [optional] # noqa: E501 - replicas (int): [optional] # noqa: E501 - shards (int): [optional] # noqa: E501 - pod_type (str): [optional] # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - """ - - metric = kwargs.get('metric', "cosine") - _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 ApiTypeError( - "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.dimension = dimension - self.capacity_mode = capacity_mode - self.metric = metric - 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, dimension, capacity_mode, *args, **kwargs): # noqa: E501 - """IndexMetaDatabase - a model defined in OpenAPI - - Args: - name (str): - dimension (int): - capacity_mode (str): - - Keyword Args: - metric (str): defaults to "cosine" # 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,) - index_type (str): [optional] # noqa: E501 - pods (int): [optional] # noqa: E501 - replicas (int): [optional] # noqa: E501 - shards (int): [optional] # noqa: E501 - pod_type (str): [optional] # noqa: E501 - index_config (dict): [optional] # noqa: E501 - metadata_config ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - """ - - metric = kwargs.get('metric', "cosine") - _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 ApiTypeError( - "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.dimension = dimension - self.capacity_mode = capacity_mode - self.metric = metric - 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 ApiAttributeError(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/client/model/index_metric.py b/pinecone/core/client/model/index_metric.py new file mode 100644 index 000000000..989d34f0c --- /dev/null +++ b/pinecone/core/client/model/index_metric.py @@ -0,0 +1,289 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class IndexMetric(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IndexMetric - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + + Keyword Args: + value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """IndexMetric - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + + Keyword Args: + value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/index_model.py b/pinecone/core/client/model/index_model.py new file mode 100644 index 000000000..eb3eeab5f --- /dev/null +++ b/pinecone/core/client/model/index_model.py @@ -0,0 +1,297 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.index_dimension import IndexDimension + from pinecone.core.client.model.index_metric import IndexMetric + from pinecone.core.client.model.index_model_spec import IndexModelSpec + from pinecone.core.client.model.index_model_status import IndexModelStatus + globals()['IndexDimension'] = IndexDimension + globals()['IndexMetric'] = IndexMetric + globals()['IndexModelSpec'] = IndexModelSpec + globals()['IndexModelStatus'] = IndexModelStatus + + +class IndexModel(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'name': (str,), # noqa: E501 + 'dimension': (IndexDimension,), # noqa: E501 + 'metric': (IndexMetric,), # noqa: E501 + 'spec': (IndexModelSpec,), # noqa: E501 + 'status': (IndexModelStatus,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'dimension': 'dimension', # noqa: E501 + 'metric': 'metric', # noqa: E501 + 'spec': 'spec', # noqa: E501 + 'status': 'status', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, dimension, metric, spec, status, *args, **kwargs): # noqa: E501 + """IndexModel - a model defined in OpenAPI + + Args: + name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. + dimension (IndexDimension): + metric (IndexMetric): + spec (IndexModelSpec): + status (IndexModelStatus): + + 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 ApiTypeError( + "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.dimension = dimension + self.metric = metric + self.spec = spec + self.status = status + 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, dimension, metric, spec, status, *args, **kwargs): # noqa: E501 + """IndexModel - a model defined in OpenAPI + + Args: + name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. + dimension (IndexDimension): + metric (IndexMetric): + spec (IndexModelSpec): + status (IndexModelStatus): + + 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 ApiTypeError( + "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.dimension = dimension + self.metric = metric + self.spec = spec + self.status = status + 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 ApiAttributeError(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/client/model/index_model_spec.py b/pinecone/core/client/model/index_model_spec.py new file mode 100644 index 000000000..1a15d873f --- /dev/null +++ b/pinecone/core/client/model/index_model_spec.py @@ -0,0 +1,267 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.pod_spec import PodSpec + from pinecone.core.client.model.serverless_spec import ServerlessSpec + globals()['PodSpec'] = PodSpec + globals()['ServerlessSpec'] = ServerlessSpec + + +class IndexModelSpec(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pod': (PodSpec,), # noqa: E501 + 'serverless': (ServerlessSpec,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'pod': 'pod', # noqa: E501 + 'serverless': 'serverless', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IndexModelSpec - 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,) + pod (PodSpec): [optional] # noqa: E501 + serverless (ServerlessSpec): [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 ApiTypeError( + "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 + """IndexModelSpec - 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,) + pod (PodSpec): [optional] # noqa: E501 + serverless (ServerlessSpec): [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/index_meta_status.py b/pinecone/core/client/model/index_model_status.py similarity index 92% rename from pinecone/core/client/model/index_meta_status.py rename to pinecone/core/client/model/index_model_status.py index 43c28a839..7ec7ca4ee 100644 --- a/pinecone/core/client/model/index_meta_status.py +++ b/pinecone/core/client/model/index_model_status.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -31,7 +30,7 @@ -class IndexMetaStatus(ModelNormal): +class IndexModelStatus(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -94,8 +93,6 @@ def openapi_types(): return { 'ready': (bool,), # noqa: E501 'state': (str,), # noqa: E501 - 'host': (str,), # noqa: E501 - 'port': (int,), # noqa: E501 } @cached_property @@ -106,8 +103,6 @@ def discriminator(): attribute_map = { 'ready': 'ready', # noqa: E501 'state': 'state', # noqa: E501 - 'host': 'host', # noqa: E501 - 'port': 'port', # noqa: E501 } read_only_vars = { @@ -117,14 +112,12 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, ready, state, host, port, *args, **kwargs): # noqa: E501 - """IndexMetaStatus - a model defined in OpenAPI + def _from_openapi_data(cls, ready, state, *args, **kwargs): # noqa: E501 + """IndexModelStatus - a model defined in OpenAPI Args: ready (bool): state (str): - host (str): - port (int): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -186,8 +179,6 @@ def _from_openapi_data(cls, ready, state, host, port, *args, **kwargs): # noqa: self.ready = ready self.state = state - self.host = host - self.port = port for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -208,14 +199,12 @@ def _from_openapi_data(cls, ready, state, host, port, *args, **kwargs): # noqa: ]) @convert_js_args_to_python_args - def __init__(self, ready, state, host, port, *args, **kwargs): # noqa: E501 - """IndexMetaStatus - a model defined in OpenAPI + def __init__(self, ready, state, *args, **kwargs): # noqa: E501 + """IndexModelStatus - a model defined in OpenAPI Args: ready (bool): state (str): - host (str): - port (int): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -275,8 +264,6 @@ def __init__(self, ready, state, host, port, *args, **kwargs): # noqa: E501 self.ready = ready self.state = state - self.host = host - self.port = port for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/namespace_summary.py b/pinecone/core/client/model/namespace_summary.py index 33633f796..c42d8b5a7 100644 --- a/pinecone/core/client/model/namespace_summary.py +++ b/pinecone/core/client/model/namespace_summary.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/pod_spec.py b/pinecone/core/client/model/pod_spec.py new file mode 100644 index 000000000..bc54f1514 --- /dev/null +++ b/pinecone/core/client/model/pod_spec.py @@ -0,0 +1,296 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + +def lazy_import(): + from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig + from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType + from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas + from pinecone.core.client.model.pod_spec_shards import PodSpecShards + globals()['PodSpecMetadataConfig'] = PodSpecMetadataConfig + globals()['PodSpecPodType'] = PodSpecPodType + globals()['PodSpecReplicas'] = PodSpecReplicas + globals()['PodSpecShards'] = PodSpecShards + + +class PodSpec(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 = { + ('pods',): { + '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 + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'environment': (str,), # noqa: E501 + 'replicas': (PodSpecReplicas,), # noqa: E501 + 'shards': (PodSpecShards,), # noqa: E501 + 'pod_type': (PodSpecPodType,), # noqa: E501 + 'pods': (int,), # noqa: E501 + 'metadata_config': (PodSpecMetadataConfig,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'environment': 'environment', # noqa: E501 + 'replicas': 'replicas', # noqa: E501 + 'shards': 'shards', # noqa: E501 + 'pod_type': 'pod_type', # noqa: E501 + 'pods': 'pods', # noqa: E501 + 'metadata_config': 'metadata_config', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 + """PodSpec - a model defined in OpenAPI + + Args: + environment (str): The environment where the index is hosted. + + 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,) + replicas (PodSpecReplicas): [optional] # noqa: E501 + shards (PodSpecShards): [optional] # noqa: E501 + pod_type (PodSpecPodType): [optional] # noqa: E501 + pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. [optional] # noqa: E501 + metadata_config (PodSpecMetadataConfig): [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 ApiTypeError( + "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.environment = environment + 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, environment, *args, **kwargs): # noqa: E501 + """PodSpec - a model defined in OpenAPI + + Args: + environment (str): The environment where the index is hosted. + + 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,) + replicas (PodSpecReplicas): [optional] # noqa: E501 + shards (PodSpecShards): [optional] # noqa: E501 + pod_type (PodSpecPodType): [optional] # noqa: E501 + pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. [optional] # noqa: E501 + metadata_config (PodSpecMetadataConfig): [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 ApiTypeError( + "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.environment = environment + 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 ApiAttributeError(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/client/model/pod_spec_metadata_config.py b/pinecone/core/client/model/pod_spec_metadata_config.py new file mode 100644 index 000000000..b41a51f3f --- /dev/null +++ b/pinecone/core/client/model/pod_spec_metadata_config.py @@ -0,0 +1,255 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class PodSpecMetadataConfig(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'indexed': ([str],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'indexed': 'indexed', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """PodSpecMetadataConfig - 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,) + indexed ([str]): By default, all metadata is indexed; to change this behavior, use this property to specify an array of metadata fields which should be indexed.. [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 ApiTypeError( + "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 + """PodSpecMetadataConfig - 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,) + indexed ([str]): By default, all metadata is indexed; to change this behavior, use this property to specify an array of metadata fields which should be indexed.. [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 ApiTypeError( + "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 ApiAttributeError(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/client/model/pod_spec_pod_type.py b/pinecone/core/client/model/pod_spec_pod_type.py new file mode 100644 index 000000000..120642ee3 --- /dev/null +++ b/pinecone/core/client/model/pod_spec_pod_type.py @@ -0,0 +1,290 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class PodSpecPodType(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'S1.X1': "s1.x1", + 'S1.X2': "s1.x2", + 'S1.X4': "s1.x4", + 'S1.X8': "s1.x8", + 'P1.X1': "p1.x1", + 'P1.X2': "p1.x2", + 'P1.X4': "p1.x4", + 'P1.X8': "p1.x8", + 'P2.X1': "p2.x1", + 'P2.X2': "p2.x2", + 'P2.X4': "p2.x4", + 'P2.X8': "p2.x8", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """PodSpecPodType - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + + Keyword Args: + value (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "p1.x1" + + _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 ApiTypeError( + "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 ApiTypeError( + "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): + """PodSpecPodType - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + + Keyword Args: + value (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "p1.x1" + + _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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/pod_spec_replicas.py b/pinecone/core/client/model/pod_spec_replicas.py new file mode 100644 index 000000000..44ab8f5ac --- /dev/null +++ b/pinecone/core/client/model/pod_spec_replicas.py @@ -0,0 +1,287 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class PodSpecReplicas(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',): { + '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @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): + """PodSpecReplicas - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # noqa: E501 + + Keyword Args: + value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """PodSpecReplicas - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # noqa: E501 + + Keyword Args: + value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/pod_spec_shards.py b/pinecone/core/client/model/pod_spec_shards.py new file mode 100644 index 000000000..c434e207f --- /dev/null +++ b/pinecone/core/client/model/pod_spec_shards.py @@ -0,0 +1,287 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class PodSpecShards(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',): { + '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @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): + """PodSpecShards - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # noqa: E501 + + Keyword Args: + value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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): + """PodSpecShards - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # noqa: E501 + + Keyword Args: + value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # 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 ApiTypeError( + "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 ApiTypeError( + "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 ApiTypeError( + "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/client/model/protobuf_any.py b/pinecone/core/client/model/protobuf_any.py index 365f5064c..fb46af753 100644 --- a/pinecone/core/client/model/protobuf_any.py +++ b/pinecone/core/client/model/protobuf_any.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/protobuf_null_value.py b/pinecone/core/client/model/protobuf_null_value.py index 63129117d..83e635111 100644 --- a/pinecone/core/client/model/protobuf_null_value.py +++ b/pinecone/core/client/model/protobuf_null_value.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/query_request.py b/pinecone/core/client/model/query_request.py index 774d06f73..e5a209480 100644 --- a/pinecone/core/client/model/query_request.py +++ b/pinecone/core/client/model/query_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/query_response.py b/pinecone/core/client/model/query_response.py index 886c93000..49e28d999 100644 --- a/pinecone/core/client/model/query_response.py +++ b/pinecone/core/client/model/query_response.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/query_vector.py b/pinecone/core/client/model/query_vector.py index b7220d5d9..62c5bb713 100644 --- a/pinecone/core/client/model/query_vector.py +++ b/pinecone/core/client/model/query_vector.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/rpc_status.py b/pinecone/core/client/model/rpc_status.py index 30ff15f95..aa3f851e9 100644 --- a/pinecone/core/client/model/rpc_status.py +++ b/pinecone/core/client/model/rpc_status.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/scored_vector.py b/pinecone/core/client/model/scored_vector.py index 88cd807db..69828a242 100644 --- a/pinecone/core/client/model/scored_vector.py +++ b/pinecone/core/client/model/scored_vector.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/serverless_spec.py b/pinecone/core/client/model/serverless_spec.py new file mode 100644 index 000000000..af9792912 --- /dev/null +++ b/pinecone/core/client/model/serverless_spec.py @@ -0,0 +1,272 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + ApiTypeError, + 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 ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import ApiAttributeError + + + +class ServerlessSpec(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 = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cloud': (str,), # noqa: E501 + 'region': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'cloud': 'cloud', # noqa: E501 + 'region': 'region', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cloud, region, *args, **kwargs): # noqa: E501 + """ServerlessSpec - a model defined in OpenAPI + + Args: + cloud (str): The public cloud where you would like your index hosted + region (str): The region where you would like your index to be created. Different cloud providers have different regions available. + + 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 ApiTypeError( + "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.cloud = cloud + self.region = region + 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, cloud, region, *args, **kwargs): # noqa: E501 + """ServerlessSpec - a model defined in OpenAPI + + Args: + cloud (str): The public cloud where you would like your index hosted + region (str): The region where you would like your index to be created. Different cloud providers have different regions available. + + 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 ApiTypeError( + "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.cloud = cloud + self.region = region + 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 ApiAttributeError(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/client/model/single_query_results.py b/pinecone/core/client/model/single_query_results.py index 0c7415621..9fe8c4313 100644 --- a/pinecone/core/client/model/single_query_results.py +++ b/pinecone/core/client/model/single_query_results.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/sparse_values.py b/pinecone/core/client/model/sparse_values.py index 4d619531a..62374846e 100644 --- a/pinecone/core/client/model/sparse_values.py +++ b/pinecone/core/client/model/sparse_values.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/update_request.py b/pinecone/core/client/model/update_request.py index 1aec2bd88..3fb151e8c 100644 --- a/pinecone/core/client/model/update_request.py +++ b/pinecone/core/client/model/update_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/upsert_request.py b/pinecone/core/client/model/upsert_request.py index 0ebf0aaed..5e20e01ee 100644 --- a/pinecone/core/client/model/upsert_request.py +++ b/pinecone/core/client/model/upsert_request.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/upsert_response.py b/pinecone/core/client/model/upsert_response.py index 831fb39bb..3a0c766cc 100644 --- a/pinecone/core/client/model/upsert_response.py +++ b/pinecone/core/client/model/upsert_response.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model/vector.py b/pinecone/core/client/model/vector.py index e3aef790a..7c94ea867 100644 --- a/pinecone/core/client/model/vector.py +++ b/pinecone/core/client/model/vector.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/model_utils.py b/pinecone/core/client/model_utils.py index 940cc93a1..f07308a93 100644 --- a/pinecone/core/client/model_utils.py +++ b/pinecone/core/client/model_utils.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/client/models/__init__.py b/pinecone/core/client/models/__init__.py index b514eb36f..8cb83d215 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -9,22 +9,33 @@ # import sys # sys.setrecursionlimit(n) -from pinecone.core.client.model.approximated_config import ApproximatedConfig -from pinecone.core.client.model.collection_meta import CollectionMeta +from pinecone.core.client.model.aws_regions import AwsRegions +from pinecone.core.client.model.collection_list import CollectionList +from pinecone.core.client.model.collection_model import CollectionModel +from pinecone.core.client.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.client.model.configure_index_request_spec import ConfigureIndexRequestSpec +from pinecone.core.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_request import CreateRequest +from pinecone.core.client.model.create_index_request import CreateIndexRequest from pinecone.core.client.model.delete_request import DeleteRequest from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.client.model.error_response import ErrorResponse +from pinecone.core.client.model.error_response_error import ErrorResponseError from pinecone.core.client.model.fetch_response import FetchResponse -from pinecone.core.client.model.hnsw_config import HnswConfig -from pinecone.core.client.model.index_list_meta import IndexListMeta -from pinecone.core.client.model.index_meta import IndexMeta -from pinecone.core.client.model.index_meta_database import IndexMetaDatabase -from pinecone.core.client.model.index_meta_status import IndexMetaStatus -from pinecone.core.client.model.inline_response200 import InlineResponse200 +from pinecone.core.client.model.gcp_regions import GcpRegions +from pinecone.core.client.model.index_dimension import IndexDimension +from pinecone.core.client.model.index_list import IndexList +from pinecone.core.client.model.index_metric import IndexMetric +from pinecone.core.client.model.index_model import IndexModel +from pinecone.core.client.model.index_model_spec import IndexModelSpec +from pinecone.core.client.model.index_model_status import IndexModelStatus from pinecone.core.client.model.namespace_summary import NamespaceSummary -from pinecone.core.client.model.patch_request import PatchRequest +from pinecone.core.client.model.pod_spec import PodSpec +from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig +from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType +from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas +from pinecone.core.client.model.pod_spec_shards import PodSpecShards from pinecone.core.client.model.protobuf_any import ProtobufAny from pinecone.core.client.model.protobuf_null_value import ProtobufNullValue from pinecone.core.client.model.query_request import QueryRequest @@ -32,6 +43,7 @@ from pinecone.core.client.model.query_vector import QueryVector from pinecone.core.client.model.rpc_status import RpcStatus from pinecone.core.client.model.scored_vector import ScoredVector +from pinecone.core.client.model.serverless_spec import ServerlessSpec from pinecone.core.client.model.single_query_results import SingleQueryResults from pinecone.core.client.model.sparse_values import SparseValues from pinecone.core.client.model.update_request import UpdateRequest diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index 8a9aafcb6..eed678cbf 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -1,10 +1,9 @@ """ - Pinecone API + Pineonce.io Public API - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + 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: version not set - Contact: support@pinecone.io + The version of the OpenAPI document: 1.0 Generated by: https://openapi-generator.tech """ @@ -14,6 +13,7 @@ import logging import re import ssl +import os from urllib.parse import urlencode import urllib3 @@ -21,6 +21,17 @@ from pinecone.core.client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError +class bcolors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + logger = logging.getLogger(__name__) @@ -121,6 +132,20 @@ def request(self, method, url, query_params=None, headers=None, assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] + if os.environ.get('PINECONE_DEBUG_CURL'): + formatted_headers = ' '.join(["-H '{0}: {1}'".format(k, v) + for k, v in headers.items()]) + formatted_query = urlencode(query_params) + if formatted_query: + formatted_url = f'{url}?{formatted_query}' + else: + formatted_url = url + if body is None: + print(bcolors.OKBLUE + "curl -X {method} '{url}' {formatted_headers}".format(method=method, url=formatted_url, formatted_headers=formatted_headers) + bcolors.ENDC) + else: + formatted_body = json.dumps(body) + print(bcolors.OKBLUE + "curl -X {method} '{url}' {formatted_headers} -d '{data}'".format(method=method, url=formatted_url, formatted_headers=formatted_headers, data=formatted_body) + bcolors.ENDC) + if post_params and body: raise ApiValueError( "body parameter cannot be used with post_params parameter." @@ -204,9 +229,18 @@ def request(self, method, url, query_params=None, headers=None, msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - if _preload_content: + if os.environ.get('PINECONE_DEBUG_CURL'): r = RESTResponse(r) + if r.status <= 300: + print(bcolors.OKGREEN + r.data.decode('utf-8') + bcolors.ENDC) + else: + print(bcolors.FAIL + r.data.decode('utf-8') + bcolors.ENDC) + + + if _preload_content: + r = RESTResponse(r) + # log response body logger.debug("response body: %s", r.data) diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py new file mode 100644 index 000000000..50cb959e0 --- /dev/null +++ b/pinecone/models/__init__.py @@ -0,0 +1,12 @@ +from .index_description import IndexDescription, IndexStatus, PodSpec, PodSpecDefinition, ServerlessSpec, ServerlessSpecDefinition +from .collection_description import CollectionDescription + +__all__ = [ + 'CollectionDescription', + 'IndexDescription', + 'IndexStatus', + 'PodSpec', + 'PodSpecDefinition', + 'ServerlessSpec', + 'ServerlessSpecDefinition' +] \ No newline at end of file diff --git a/pinecone/models/collection_description.py b/pinecone/models/collection_description.py new file mode 100644 index 000000000..44c5f51e0 --- /dev/null +++ b/pinecone/models/collection_description.py @@ -0,0 +1,5 @@ +from typing import NamedTuple + +class CollectionDescription(NamedTuple): + name: str + source: str \ No newline at end of file diff --git a/pinecone/models/index_description.py b/pinecone/models/index_description.py new file mode 100644 index 000000000..8135241d7 --- /dev/null +++ b/pinecone/models/index_description.py @@ -0,0 +1,31 @@ +from typing import NamedTuple, Dict, Optional, Union, Literal + +class IndexStatus(NamedTuple): + state: str + ready: bool + +PodKey = Literal['pod'] +class PodSpecDefinition(NamedTuple): + replicas: int + shards: int + pods: int + pod_type: str + environment: str + metadata_config: Optional[Dict] + +PodSpec = Dict[PodKey, PodSpecDefinition] + +ServerlessKey = Literal['serverless'] +class ServerlessSpecDefinition(NamedTuple): + cloud: str + region: str + +ServerlessSpec = Dict[ServerlessKey, ServerlessSpecDefinition] + +class IndexDescription(NamedTuple): + name: str + dimension: int + metric: str + host: str + spec: Union[PodSpec, ServerlessSpec] + status: IndexStatus diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 000000000..09bfaba85 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,80 @@ +import pytest +from pinecone import Pinecone +from .helpers.helpers import generate_index_name, get_environment_var + +@pytest.fixture() +def client(): + api_key = get_environment_var('PINECONE_API_KEY') + return Pinecone(api_key=api_key) + +@pytest.fixture() +def environment(): + return get_environment_var('PINECONE_ENVIRONMENT') + +@pytest.fixture() +def create_sl_index_params(index_name): + spec = { + 'cloud': 'aws', + 'region': 'us-east1' + } + return dict(name=index_name, dimension=10, metric='cosine', spec=spec, timeout=-1) + +@pytest.fixture() +def create_pod_index_params(index_name, environment): + spec = { + 'environment': environment + } + return dict(name=index_name, dimension=10, metric='cosine', spec=spec, timeout=-1) + +@pytest.fixture() +def index_name(request): + test_name = request.node.name + return generate_index_name(test_name) + +@pytest.fixture() +def ready_sl_index(client, index_name, create_sl_index_params): + del create_sl_index_params['timeout'] + client.create_index(**create_sl_index_params) + yield index_name + client.delete_index(index_name, -1) + +@pytest.fixture() +def notready_sl_index(client, index_name, create_sl_index_params): + client.create_index(**create_sl_index_params) + yield index_name + client.delete_index(index_name, -1) + +@pytest.fixture() +def ready_pod_index(client, index_name, create_pod_index_params): + del create_pod_index_params['timeout'] + client.create_index(**create_pod_index_params) + yield index_name + client.delete_index(index_name, -1) + +@pytest.fixture() +def notready_pod_index(client, index_name, create_pod_index_params): + client.create_index(**create_pod_index_params) + yield index_name + client.delete_index(index_name, -1) + +@pytest.fixture(autouse=True) +def cleanup(client, index_name): + yield + + client.delete_index(index_name, -1) + + try: + client.delete_index(index_name, -1) + except: + pass + +@pytest.fixture(autouse=True, scope='session') +def cleanup_all(): + yield + + client = Pinecone() + for index in client.list_indexes().databases: + try: + client.delete_index(index.name, -1) + except: + pass \ No newline at end of file diff --git a/tests/integration/helpers/__init__.py b/tests/integration/helpers/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/helpers/helpers.py b/tests/integration/helpers/helpers.py new file mode 100644 index 000000000..1e40f6fac --- /dev/null +++ b/tests/integration/helpers/helpers.py @@ -0,0 +1,45 @@ +import re +import os +import random +import string + +def random_string(length): + return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) + +def generate_index_name(test_name: str) -> str: + buildNumber = os.getenv('GITHUB_BUILD_NUMBER', None) + + if test_name.startswith('test_'): + test_name = test_name[5:] + + # Trim name length to save space for other info in name + test_name = test_name[:20] + + # Remove trailing underscore, if any + if test_name.endswith('_'): + test_name = test_name[:-1] + + name_parts = [buildNumber, test_name, random_string(45)] + index_name = '-'.join([x for x in name_parts if x is not None]) + + # Remove invalid characters + replace_with_hyphen = re.compile(r'[\[\(_,\s]') + index_name = re.sub(replace_with_hyphen, '-', index_name) + replace_with_empty = re.compile(r'[\]\)\.]') + index_name = re.sub(replace_with_empty, '', index_name) + + max_length = 45 + index_name = index_name[:max_length] + + # Trim final character if it is not alphanumeric + if test_name.endswith('_') or test_name.endswith('-'): + test_name = test_name[:-1] + + return index_name.lower() + +def get_environment_var(name: str) -> str: + val = os.getenv(name) + if (val is None): + raise Exception('Expected environment variable ' + name + ' is not set') + else: + return val diff --git a/tests/integration/test_collections.py b/tests/integration/test_collections.py new file mode 100644 index 000000000..976724540 --- /dev/null +++ b/tests/integration/test_collections.py @@ -0,0 +1,39 @@ +import pytest +from pinecone import CollectionDescription + +@pytest.mark.skip() +class TestCollection: + def test_create_collection_from_ready_index_w_data(self, client, ready_index): + index = client.Index(ready_index) + index.upsert([{'id': '1', 'values': [0.1, 0.2]}]) + + name = 'test_collection' + client.create_collection(name, ready_index) + desc = client.describe_collection(name) + assert type(desc) == CollectionDescription + assert desc.name == name + assert desc.index == ready_index + + client.delete_collection(name) + + def test_create_collection_from_ready_index_w_no_data(self, client, ready_index): + name = 'test_collection' + client.create_collection(name, ready_index) + desc = client.describe_collection(name) + assert type(desc) == CollectionDescription + assert desc.name == name + assert desc.index == ready_index + + client.delete_collection(name) + + def test_create_collection_from_not_ready_index(self, client, notready_index): + name = 'test_collection' + with pytest.raises(Exception) as e: + client.create_collection(name, notready_index) + assert 'Index is not ready' in str(e.value) + + def test_create_collection_with_invalid_index(self, client): + name = 'test_collection' + with pytest.raises(Exception) as e: + client.create_collection(name, 'invalid_index') + assert 'Index not found' in str(e.value) \ No newline at end of file diff --git a/tests/integration/test_create_index_api_errors.py b/tests/integration/test_create_index_api_errors.py new file mode 100644 index 000000000..1e7f56a7b --- /dev/null +++ b/tests/integration/test_create_index_api_errors.py @@ -0,0 +1,31 @@ +import pytest +from pinecone import ApiException + +class TestCreateIndexApiErrorCases: + def test_create_index_with_invalid_name(self, client, create_index_params): + create_index_params['name'] = '-invalid-name' + with pytest.raises(ApiException): + client.create_index(**create_index_params) + + def test_create_index_invalid_metric(self, client, create_index_params): + create_index_params['metric'] = 'invalid' + with pytest.raises(ApiException): + client.create_index(**create_index_params) + + def test_create_index_with_invalid_neg_dimension(self, client, create_index_params): + create_index_params['dimension'] = -1 + with pytest.raises(ApiException): + client.create_index(**create_index_params) + + def test_create_index_that_already_exists(self, client, create_index_params): + client.create_index(**create_index_params) + with pytest.raises(ApiException): + client.create_index(**create_index_params) + + @pytest.mark.skip(reason='Bug filed https://app.asana.com/0/1205078872348810/1205917627868143') + def test_create_index_w_incompatible_options(self, client, create_index_params): + create_index_params['pod_type'] = 'p1.x2' + create_index_params['environment'] = 'us-east1-gcp' + create_index_params['replicas'] = 2 + with pytest.raises(ApiException): + client.create_index(**create_index_params) \ No newline at end of file diff --git a/tests/integration/test_create_index_happy_path.py b/tests/integration/test_create_index_happy_path.py new file mode 100644 index 000000000..4b813912e --- /dev/null +++ b/tests/integration/test_create_index_happy_path.py @@ -0,0 +1,18 @@ +import pytest + +class TestCreateSLIndexHappyPath: + def test_create_index(self, client, create_sl_index_params): + name = create_sl_index_params['name'] + dimension = create_sl_index_params['dimension'] + client.create_index(**create_sl_index_params) + desc = client.describe_index(name) + assert desc.name == name + assert desc.dimension == dimension + assert desc.metric == 'cosine' + + @pytest.mark.parametrize('metric', ['cosine', 'euclidean', 'dotproduct']) + def test_create_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 \ No newline at end of file diff --git a/tests/integration/test_create_index_timeouts.py b/tests/integration/test_create_index_timeouts.py new file mode 100644 index 000000000..e9d5b4137 --- /dev/null +++ b/tests/integration/test_create_index_timeouts.py @@ -0,0 +1,28 @@ +import pytest + +class TestCreateIndexWithTimeout: + def test_create_index_default_timeout(self, client, create_sl_index_params): + del create_sl_index_params['timeout'] + client.create_index(**create_sl_index_params) + # Waits infinitely for index to be ready + desc = client.describe_index(create_sl_index_params['name']) + assert desc.status.ready == True + + def test_create_index_when_timeout_set(self, client, create_sl_index_params): + create_sl_index_params['timeout'] = 1000 # effectively infinite, but different code path from None + client.create_index(**create_sl_index_params) + desc = client.describe_index(create_sl_index_params['name']) + assert desc.status.ready == True + + def test_create_index_when_timeout_error(self, client, create_sl_index_params): + create_sl_index_params['timeout'] = 1 + with pytest.raises(TimeoutError): + client.create_index(**create_sl_index_params) + + def test_create_index_with_negative_timeout(self, client, create_sl_index_params): + create_sl_index_params['timeout'] = -1 + client.create_index(**create_sl_index_params) + desc = client.describe_index(create_sl_index_params['name']) + # Returns immediately without waiting for index to be ready + assert desc.status.ready == False + diff --git a/tests/integration/test_create_index_type_errors.py b/tests/integration/test_create_index_type_errors.py new file mode 100644 index 000000000..b4f649c07 --- /dev/null +++ b/tests/integration/test_create_index_type_errors.py @@ -0,0 +1,13 @@ +import pytest +from pinecone import ApiTypeError + +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(ApiTypeError): + client.create_index(**create_sl_index_params) + + def test_create_index_with_missing_dimension(self, client, create_sl_index_params): + del create_sl_index_params['dimension'] + with pytest.raises(TypeError): + client.create_index(**create_sl_index_params) \ No newline at end of file diff --git a/tests/integration/test_describe_index.py b/tests/integration/test_describe_index.py new file mode 100644 index 000000000..0e1cecb36 --- /dev/null +++ b/tests/integration/test_describe_index.py @@ -0,0 +1,30 @@ +import pytest +from pinecone import IndexDescription + +class TestDescribeIndex: + def test_describe_index_when_ready(self, client, ready_sl_index, create_sl_index_params): + description = client.describe_index(ready_sl_index) + assert type(description) == IndexDescription + assert description.name == ready_sl_index + assert description.dimension == create_sl_index_params['dimension'] + assert description.metric == create_sl_index_params['metric'] + assert description.capacity_mode == create_sl_index_params['capacity_mode'] + + assert type(description.status.host) == str + assert description.status.host != "" + assert description.status.state == 'Ready' + assert ready_sl_index in description.status.host + assert description.status.ready == True + + def test_describe_index_when_not_ready(self, client, notready_sl_index, create_sl_index_params): + description = client.describe_index(notready_sl_index) + + assert type(description) == IndexDescription + assert description.name == notready_sl_index + assert description.dimension == create_sl_index_params['dimension'] + assert description.metric == create_sl_index_params['metric'] + + assert type(description.status.host) == str + assert description.status.host != "" + assert notready_sl_index in description.status.host + assert description.status.ready == False \ No newline at end of file diff --git a/tests/integration/test_list_indexes.py b/tests/integration/test_list_indexes.py new file mode 100644 index 000000000..66fa39e19 --- /dev/null +++ b/tests/integration/test_list_indexes.py @@ -0,0 +1,23 @@ +from pinecone import IndexModel + +class TestListIndexes(): + def test_list_indexes_includes_ready_indexes(self, client, ready_index, create_index_params): + list_response = client.list_indexes() + assert len(list_response.indexes) != 0 + assert type(list_response.indexes[0]) == IndexModel + + created_index = [index for index in list_response.indexes if index.name == ready_index][0] + assert created_index.name == ready_index + assert created_index.dimension == create_index_params['dimension'] + assert created_index.metric == create_index_params['metric'] + assert ready_index in created_index.host + assert created_index.capacity_mode == create_index_params['capacity_mode'] + + def test_list_indexes_includes_not_ready_indexes(self, client, notready_index): + list_response = client.list_indexes() + assert len(list_response.indexes) != 0 + assert type(list_response.indexes[0]) == IndexModel + + created_index = [index for index in list_response.indexes if index.name == notready_index][0] + assert created_index.name == notready_index + assert notready_index in created_index.name diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 1d54e736b..1b3e2fc56 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -28,7 +28,7 @@ def test_create_index_with_timeout(self, mocker, timeout_value, describe_index_r mocker.patch.object(p.index_api, 'create_index') mocker.patch('time.sleep') - p.create_index("my-index", 10, timeout=timeout_value, cloud="aws", region="us-west1", capacity_mode="pod") + p.create_serverless_index(name="my-index", dimension=10, cloud="aws", region="us-west1", timeout=timeout_value) assert p.index_api.create_index.call_count == 1 assert p.index_api.describe_index.call_count == expected_describe_index_calls @@ -43,4 +43,4 @@ def test_create_index_when_timeout_exceeded(self, mocker): mocker.patch.object(p.index_api, 'describe_index', side_effect=describe_index_response) mocker.patch('time.sleep') - p.create_index("my-index", 10, timeout=10, cloud="aws", region="us-west1", capacity_mode="pod") + p.create_pod_index(name="my-index", dimension=10, timeout=10, environment="us-west1-gcp") From a851d64e4d5d058b7106037c9f55abb859f9ec81 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Sun, 19 Nov 2023 16:46:02 -0500 Subject: [PATCH 12/39] [spruce] Add additional_headers config (#245) --- pinecone/config/config.py | 8 +++++--- pinecone/config/pinecone_config.py | 6 +++--- pinecone/control/pinecone.py | 6 +++++- tests/unit/test_control.py | 6 ++++++ 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/pinecone/config/config.py b/pinecone/config/config.py index 0b31e10f3..2bd851419 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -1,4 +1,4 @@ -from typing import NamedTuple, Optional +from typing import NamedTuple, Optional, Dict import os from pinecone.exceptions import PineconeConfigurationError @@ -11,7 +11,8 @@ class Config(NamedTuple): api_key: str = "" host: str = "" openapi_config: Optional[OpenApiConfiguration] = None - + additional_headers: Optional[Dict[str, str]] = {} + class ConfigBuilder: """ @@ -35,6 +36,7 @@ def build( api_key: Optional[str] = None, host: Optional[str] = None, openapi_config: Optional[OpenApiConfiguration] = None, + additional_headers: Optional[Dict[str, str]] = {}, **kwargs, ) -> Config: api_key = api_key or kwargs.pop("api_key", None) or os.getenv("PINECONE_API_KEY") @@ -51,4 +53,4 @@ def build( or OpenApiConfigFactory.build(api_key=api_key, host=host) ) - return Config(api_key, host, openapi_config) \ No newline at end of file + return Config(api_key, host, openapi_config, additional_headers) \ No newline at end of file diff --git a/pinecone/config/pinecone_config.py b/pinecone/config/pinecone_config.py index 024431ed8..ccf0b2126 100644 --- a/pinecone/config/pinecone_config.py +++ b/pinecone/config/pinecone_config.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, Dict import os from .config import ConfigBuilder, Config @@ -7,6 +7,6 @@ class PineconeConfig(): @staticmethod - def build(api_key: Optional[str] = None, host: Optional[str] = None, **kwargs) -> Config: + def build(api_key: Optional[str] = None, host: Optional[str] = None, additional_headers: Optional[Dict[str, str]] = {}, **kwargs) -> Config: host = host or kwargs.get("host") or os.getenv("PINECONE_CONTROLLER_HOST") or DEFAULT_CONTROLLER_HOST - return ConfigBuilder.build(api_key=api_key, host=host, **kwargs) + return ConfigBuilder.build(api_key=api_key, host=host, additional_headers=additional_headers, **kwargs) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index c2d83489f..8d84e9bd2 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -25,6 +25,7 @@ def __init__( api_key: Optional[str] = None, host: Optional[str] = None, config: Optional[Config] = None, + additional_headers: Optional[Dict[str, str]] = {}, index_api: Optional[IndexOperationsApi] = None, **kwargs, ): @@ -35,13 +36,16 @@ def __init__( else: self.config = configKwarg else: - self.config = PineconeConfig.build(api_key=api_key, host=host, **kwargs) + self.config = PineconeConfig.build(api_key=api_key, host=host, additional_headers=additional_headers, **kwargs) if index_api: self.index_api = index_api else: api_client = ApiClient(configuration=self.config.openapi_config) api_client.user_agent = get_user_agent() + extra_headers = self.config.additional_headers or {} + for key, value in extra_headers.items(): + api_client.set_default_header(key, value) self.index_api = IndexOperationsApi(api_client) self.index_host_store = IndexHostStore() diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 1b3e2fc56..aa2d749f7 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -11,6 +11,12 @@ def test_passing_host(self): p = Pinecone(api_key="123-456-789", host="my-host") assert p.index_api.api_client.configuration.host == "my-host" + def test_passing_additional_headers(self): + extras = {"header1": "my-value", "header2": "my-value2"} + p = Pinecone(api_key="123-456-789", additional_headers=extras) + + for key, value in extras.items(): + assert p.index_api.api_client.default_headers[key] == value @pytest.mark.parametrize("timeout_value, describe_index_responses, expected_describe_index_calls, expected_sleep_calls", [ # When timeout=None, describe_index is called until ready From b6da95f075568c05fd5deafd595d775670a37e1b Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 20 Nov 2023 17:37:03 -0500 Subject: [PATCH 13/39] Fix typo in debug print code --- pinecone/core/client/rest.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index eed678cbf..7e041c58a 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -230,12 +230,12 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) if os.environ.get('PINECONE_DEBUG_CURL'): - r = RESTResponse(r) + o = RESTResponse(r) - if r.status <= 300: - print(bcolors.OKGREEN + r.data.decode('utf-8') + bcolors.ENDC) + if o.status <= 300: + print(bcolors.OKGREEN + o.data.decode('utf-8') + bcolors.ENDC) else: - print(bcolors.FAIL + r.data.decode('utf-8') + bcolors.ENDC) + print(bcolors.FAIL + o.data.decode('utf-8') + bcolors.ENDC) if _preload_content: From e46ed604ca26638d6375101b42ef76862ed5542d Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 21 Nov 2023 14:44:34 -0500 Subject: [PATCH 14/39] Fix ServerlessSpec issue --- pinecone/__init__.py | 2 +- pinecone/control/pinecone.py | 15 +++++++++++---- pinecone/models/__init__.py | 4 +++- pinecone/models/pod_spec.py | 12 ++++++++++++ pinecone/models/serverless_spec.py | 8 ++++++++ 5 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 pinecone/models/pod_spec.py create mode 100644 pinecone/models/serverless_spec.py diff --git a/pinecone/__init__.py b/pinecone/__init__.py index fe52da72b..4ccf6d4f3 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -6,4 +6,4 @@ from .control.pinecone import Pinecone from .data.index import * from .models import * -from .core.client.models import * \ No newline at end of file +# from .core.client.models import * \ No newline at end of file diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 8d84e9bd2..832f46d87 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -13,8 +13,10 @@ CreateIndexRequest, ConfigureIndexRequest, IndexMetric, - IndexDimension + IndexDimension, ) +from pinecone.models import ServerlessSpec, PodSpec + from pinecone.data import Index @@ -75,7 +77,7 @@ def create_pod_index( metadata_config: Optional[Dict] = None, source_collection: Optional[str] = None, timeout: Optional[int] = None, - ): + ): spec_inner = dict( environment=environment, replicas=replicas, @@ -93,7 +95,7 @@ def create_index( self, name: str, dimension: int, - spec: Dict, + spec: Union[Dict, ServerlessSpec, PodSpec], metric: Optional[str] = "cosine", timeout: Optional[int] = None, ): @@ -118,7 +120,12 @@ def create_index( api_instance = self.index_api - api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec)) + if isinstance(spec, dict): + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec)) + elif isinstance(spec, ServerlessSpec): + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec.asdict())) + elif isinstance(spec, PodSpec): + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec.asdict())) def is_ready(): status = self._get_status(name) diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py index 50cb959e0..d2156160f 100644 --- a/pinecone/models/__init__.py +++ b/pinecone/models/__init__.py @@ -1,5 +1,7 @@ -from .index_description import IndexDescription, IndexStatus, PodSpec, PodSpecDefinition, ServerlessSpec, ServerlessSpecDefinition +from .index_description import IndexDescription, IndexStatus, ServerlessSpecDefinition, PodSpecDefinition from .collection_description import CollectionDescription +from .serverless_spec import ServerlessSpec +from .pod_spec import PodSpec __all__ = [ 'CollectionDescription', diff --git a/pinecone/models/pod_spec.py b/pinecone/models/pod_spec.py new file mode 100644 index 000000000..b126aefa4 --- /dev/null +++ b/pinecone/models/pod_spec.py @@ -0,0 +1,12 @@ +from typing import NamedTuple, Optional, Dict + +class PodSpec(NamedTuple): + environment: str + replicas: Optional[int] = None + shards: Optional[int] = None + pods: Optional[int] = None + pod_type: Optional[str] = "p1.x1" + metadata_config: Optional[Dict] = {} + + def asdict(self): + return {"pod": self._asdict()} \ No newline at end of file diff --git a/pinecone/models/serverless_spec.py b/pinecone/models/serverless_spec.py new file mode 100644 index 000000000..33f8fdbcc --- /dev/null +++ b/pinecone/models/serverless_spec.py @@ -0,0 +1,8 @@ +from typing import NamedTuple + +class ServerlessSpec(NamedTuple): + cloud: str + region: str + + def asdict(self): + return {"serverless": self._asdict()} \ No newline at end of file From 6980a3cad8137df623727949ef413f7bfef43dbd Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 21 Nov 2023 15:58:47 -0500 Subject: [PATCH 15/39] Fix host store bug with targeting indexes --- pinecone/control/index_host_store.py | 9 +++++-- pinecone/control/pinecone.py | 39 ---------------------------- tests/unit/test_control.py | 6 ++--- 3 files changed, 10 insertions(+), 44 deletions(-) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index 38354ee18..d27bf12af 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -24,6 +24,9 @@ def delete_host(self, config: Config, index_name: str): if key in self._indexHosts: del self._indexHosts[key] + def key_exists(self, key: str) -> bool: + return key in self._indexHosts + def set_host(self, config: Config, index_name: str, host: str): if host: key = self._key(config, index_name) @@ -31,9 +34,11 @@ def set_host(self, config: Config, index_name: str, host: str): def get_host(self, api: IndexOperationsApi, config: Config, index_name: str) -> str: key = self._key(config, index_name) - if key in self._indexHosts: + if self.key_exists(key): return self._indexHosts[key] else: description = api.describe_index(index_name) - self.set_host(config, index_name, description.status.host) + self.set_host(config, index_name, description.host) + if not self.key_exists(key): + raise Exception(f"Could not get host for index: {index_name}. Call describe_index('{index_name}') to check the current status.") return self._indexHosts[key] diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 832f46d87..618afda14 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -52,45 +52,6 @@ def __init__( self.index_host_store = IndexHostStore() - def create_serverless_index( - self, - name: str, - dimension: int, - region: str, - cloud: str, - metric: Optional[str] = "cosine", - timeout: Optional[int] = None, - ): - spec = {'serverless': dict(region=region, cloud=cloud)} - self.create_index(name=name, dimension=dimension, metric=metric, spec=spec, timeout=timeout) - - def create_pod_index( - self, - name: str, - dimension: int, - environment: str, - metric: Optional[str] = "cosine", - replicas: Optional[int] = None, - shards: Optional[int] = None, - pods: Optional[int] = None, - pod_type: Optional[str] = "p1.x1", - metadata_config: Optional[Dict] = None, - source_collection: Optional[str] = None, - timeout: Optional[int] = None, - ): - spec_inner = dict( - environment=environment, - replicas=replicas, - shards=shards, - pods=pods, - pod_type=pod_type, - metadata_config=metadata_config, - source_collection=source_collection, - ) - filtered_spec_inner = {k: v for k, v in spec_inner.items() if v is not None} - spec = {'pod': filtered_spec_inner} - self.create_index(name=name, dimension=dimension, metric=metric, spec=spec, timeout=timeout) - def create_index( self, name: str, diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index aa2d749f7..8554a9cd8 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -1,5 +1,5 @@ import pytest -from pinecone import Pinecone +from pinecone import Pinecone, PodSpec, ServerlessSpec import time class TestControl: @@ -34,7 +34,7 @@ def test_create_index_with_timeout(self, mocker, timeout_value, describe_index_r mocker.patch.object(p.index_api, 'create_index') mocker.patch('time.sleep') - p.create_serverless_index(name="my-index", dimension=10, cloud="aws", region="us-west1", timeout=timeout_value) + p.create_index(name="my-index", dimension=10, spec=ServerlessSpec(cloud="aws", region="us-west1"), timeout=timeout_value) assert p.index_api.create_index.call_count == 1 assert p.index_api.describe_index.call_count == expected_describe_index_calls @@ -49,4 +49,4 @@ def test_create_index_when_timeout_exceeded(self, mocker): mocker.patch.object(p.index_api, 'describe_index', side_effect=describe_index_response) mocker.patch('time.sleep') - p.create_pod_index(name="my-index", dimension=10, timeout=10, environment="us-west1-gcp") + p.create_index(name="my-index", dimension=10, timeout=10, spec=PodSpec(environment="us-west1-gcp")) From fc5dca2707585b4dc6043c160e7515df790c6851 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 21 Nov 2023 17:11:13 -0500 Subject: [PATCH 16/39] [Fix] Prelease CI job uses bump action to version (#246) ## Problem When we migrated to `poetry`, the prerelease job did not get updated to set prerelease versions correctly. ## Solution We need to use our action to compute the correct prerelease version. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [x] Infrastructure change (CI configs, etc) --- .github/workflows/publish-to-pypi.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-to-pypi.yaml b/.github/workflows/publish-to-pypi.yaml index 82fe9ae71..93938ffcb 100644 --- a/.github/workflows/publish-to-pypi.yaml +++ b/.github/workflows/publish-to-pypi.yaml @@ -86,7 +86,7 @@ jobs: - name: Poetry bump pyproject toml version run: | - poetry version ${{ inputs.releaseLevel }} + poetry version ${{ steps.bump.outputs.version }} - name: Build Python client run: make package From 41828e0279fc474d02f9ed741946e4eb9e1d875e Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Wed, 22 Nov 2023 12:51:58 -0500 Subject: [PATCH 17/39] [spruce] Make list results iterable (#247) ## Problem Results from list_indexes a bit annoying to work with because the object isn't iterable ## Solution Proxy the object and add methods to make it iterable. This gives most of the benefits of drilling into the response and returning the list under the `indexes` while maintaining the flexility to access any attributes that get added to `IndexList` in the future (e.g. for pagination) ## Usage ```python >>> from pinecone import Pinecone >>> p = Pinecone(api_key='API_KEY') >>> results = p.list_indexes() >>> results.__class__ ``` Use this object as if it a normal list ``` >>> len(results) 2 >>> results[0] {'dimension': 3, 'host': 'jen3-sl-126ib2q.svc.dev-aws-ram-paid.pinecone.io', 'metric': 'cosine', 'name': 'jen3-sl', 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-west-2'}}, 'status': {'ready': True, 'state': 'Ready'}} >>> names = [x.name for x in results] >>> names ['jen3-sl', 'jen2-sl'] ``` However the representation in the console reflects that it is an object with attributes. And those attributes can still be accessed (e.g. `results.indexes`) ``` >>> results.indexes [{'dimension': 3, 'host': 'jen3-sl-126ib2q.svc.dev-aws-ram-paid.pinecone.io', 'metric': 'cosine', 'name': 'jen3-sl', 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-west-2'}}, 'status': {'ready': True, 'state': 'Ready'}}, {'dimension': 2, 'host': 'jen2-sl-126ib2q.svc.apw5-4e34-81fa.pinecone.io', 'metric': 'cosine', 'name': 'jen2-sl', 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-west-2'}}, 'status': {'ready': False, 'state': 'Initializing'}}] >>> results {'indexes': [{'dimension': 3, 'host': 'jen3-sl-126ib2q.svc.dev-aws-ram-paid.pinecone.io', 'metric': 'cosine', 'name': 'jen3-sl', 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-west-2'}}, 'status': {'ready': True, 'state': 'Ready'}}, {'dimension': 2, 'host': 'jen2-sl-126ib2q.svc.apw5-4e34-81fa.pinecone.io', 'metric': 'cosine', 'name': 'jen2-sl', 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-west-2'}}, 'status': {'ready': False, 'state': 'Initializing'}}]} ``` ## Type of Change - [x] New feature (non-breaking change which adds functionality) ## Test Plan Added unit tests --- pinecone/control/pinecone.py | 13 +++--- pinecone/models/__init__.py | 6 ++- pinecone/models/collection_list.py | 24 ++++++++++ pinecone/models/index_list.py | 24 ++++++++++ tests/unit/models/test_collection_list.py | 30 +++++++++++++ tests/unit/models/test_index_list.py | 54 +++++++++++++++++++++++ tests/unit/test_control.py | 18 ++++++++ 7 files changed, 161 insertions(+), 8 deletions(-) create mode 100644 pinecone/models/collection_list.py create mode 100644 pinecone/models/index_list.py create mode 100644 tests/unit/models/test_collection_list.py create mode 100644 tests/unit/models/test_index_list.py diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 618afda14..7091f6235 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -15,12 +15,10 @@ IndexMetric, IndexDimension, ) -from pinecone.models import ServerlessSpec, PodSpec - +from pinecone.models import ServerlessSpec, PodSpec, IndexList, CollectionList from pinecone.data import Index - class Pinecone: def __init__( self, @@ -146,9 +144,10 @@ def get_remaining(): ) ) - def list_indexes(self): + def list_indexes(self) -> IndexList: """Lists all indexes.""" - return self.index_api.list_indexes() + response = self.index_api.list_indexes() + return IndexList(response) def describe_index(self, name: str): """Describes a Pinecone index. @@ -197,11 +196,11 @@ def create_collection(self, name: str, source: str): api_instance = self.index_api api_instance.create_collection(create_collection_request=CreateCollectionRequest(name=name, source=source)) - def list_collections(self): + def list_collections(self) -> CollectionList: """List all collections""" api_instance = self.index_api response = api_instance.list_collections() - return response + return CollectionList(response) def delete_collection(self, name: str): """Deletes a collection. diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py index d2156160f..19c506c36 100644 --- a/pinecone/models/__init__.py +++ b/pinecone/models/__init__.py @@ -2,6 +2,8 @@ from .collection_description import CollectionDescription from .serverless_spec import ServerlessSpec from .pod_spec import PodSpec +from .index_list import IndexList +from .collection_list import CollectionList __all__ = [ 'CollectionDescription', @@ -10,5 +12,7 @@ 'PodSpec', 'PodSpecDefinition', 'ServerlessSpec', - 'ServerlessSpecDefinition' + 'ServerlessSpecDefinition', + 'IndexList', + 'CollectionList' ] \ No newline at end of file diff --git a/pinecone/models/collection_list.py b/pinecone/models/collection_list.py new file mode 100644 index 000000000..64df1e57a --- /dev/null +++ b/pinecone/models/collection_list.py @@ -0,0 +1,24 @@ +from pinecone.core.client.models import CollectionList as OpenAPICollectionList + +class CollectionList: + def __init__(self, collection_list: OpenAPICollectionList): + self.collection_list = collection_list + self.current = 0 + + def __getitem__(self, key): + return self.collection_list.collections[key] + + def __len__(self): + return len(self.collection_list.collections) + + def __iter__(self): + return iter(self.collection_list.collections) + + def __str__(self): + return str(self.collection_list) + + def __repr__(self): + return repr(self.collection_list) + + def __getattr__(self, attr): + return getattr(self.collection_list, attr) \ No newline at end of file diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py new file mode 100644 index 000000000..ed1974f5c --- /dev/null +++ b/pinecone/models/index_list.py @@ -0,0 +1,24 @@ +from pinecone.core.client.models import IndexList as OpenAPIIndexList + +class IndexList: + def __init__(self, index_list: OpenAPIIndexList): + self.index_list = index_list + self.current = 0 + + def __getitem__(self, key): + return self.index_list.indexes[key] + + def __len__(self): + return len(self.index_list.indexes) + + def __iter__(self): + return iter(self.index_list.indexes) + + def __str__(self): + return str(self.index_list) + + def __repr__(self): + return repr(self.index_list) + + def __getattr__(self, attr): + return getattr(self.index_list, attr) \ No newline at end of file diff --git a/tests/unit/models/test_collection_list.py b/tests/unit/models/test_collection_list.py new file mode 100644 index 000000000..3b26690f1 --- /dev/null +++ b/tests/unit/models/test_collection_list.py @@ -0,0 +1,30 @@ +import pytest +from pinecone import CollectionList +from pinecone.core.client.models import CollectionList as OpenApiCollectionList, CollectionModel + +@pytest.fixture +def collection_list_response(): + return OpenApiCollectionList( + collections=[ + CollectionModel(name='collection1', size=10000, status='Ready', dimension=1536, record_count=1000), + CollectionModel(name='collection2', size=20000, status='Ready', dimension=256, record_count=2000), + ], + ) + +class TestCollectionList: + def test_collection_list_has_length(self, collection_list_response): + assert len(CollectionList(collection_list_response)) == 2 + + def test_collection_list_is_(self, collection_list_response): + icl = CollectionList(collection_list_response) + assert [i['name'] for i in icl] == ['collection1', 'collection2'] + assert [i.record_count for i in icl] == [1000, 2000] + + def test_collection_list_getitem(self, collection_list_response): + icl = CollectionList(collection_list_response) + assert icl[0] == collection_list_response.collections[0] + assert icl[1] == collection_list_response.collections[1] + + def test_collection_list_proxies_methods(self, collection_list_response): + # Forward compatibility, in case we add more attributes to IndexList for pagination + assert CollectionList(collection_list_response).collection_list.collections == collection_list_response.collections \ No newline at end of file diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py new file mode 100644 index 000000000..fe34b738f --- /dev/null +++ b/tests/unit/models/test_index_list.py @@ -0,0 +1,54 @@ +import pytest +from pinecone import IndexList +from pinecone.core.client.models import IndexList as OpenApiIndexList + +@pytest.fixture +def index_list_response(): + return OpenApiIndexList( + indexes=[ + { + "name": "test-index-1", + "dimension": 2, + "metric": "cosine", + "spec": { + "pod": { + "environment": "us-west1-gcp", + "pod_type": "p1.x1", + "pods": 1, + "replicas": 1, + "shards": 1 + } + } + }, + { + "name": "test-index-2", + "dimension": 2, + "metric": "cosine", + "spec": { + "serverless": { + "cloud": "aws", + "region": "us-west-2" + } + } + }, + ], _check_type=False + ) + +class TestIndexList: + def test_index_list_has_length(self, index_list_response): + assert len(IndexList(index_list_response)) == 2 + + def test_index_list_is(self, index_list_response): + iil = IndexList(index_list_response) + assert [i['name'] for i in iil] == ['test-index-1', 'test-index-2'] + + def test_index_list_getitem(self, index_list_response): + iil = IndexList(index_list_response) + assert iil[0] == index_list_response.indexes[0] + assert iil[1] == index_list_response.indexes[1] + + def test_index_list_proxies_methods(self, index_list_response): + # Forward compatibility, in case we add more attributes to IndexList for pagination + assert IndexList(index_list_response).index_list.indexes == index_list_response.indexes + + diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 8554a9cd8..570cc96f4 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -1,7 +1,17 @@ import pytest from pinecone import Pinecone, PodSpec, ServerlessSpec +from pinecone.core.client.models import IndexList, IndexModel import time +@pytest.fixture +def index_list_response(): + return IndexList(indexes=[ + IndexModel(name="index1", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), + IndexModel(name="index2", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), + IndexModel(name="index3", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), + + ]) + class TestControl: def test_default_host(self): p = Pinecone(api_key="123-456-789") @@ -50,3 +60,11 @@ def test_create_index_when_timeout_exceeded(self, mocker): mocker.patch('time.sleep') p.create_index(name="my-index", dimension=10, timeout=10, spec=PodSpec(environment="us-west1-gcp")) + + def test_list_indexes_returns_iterable(self, mocker, index_list_response): + p = Pinecone(api_key="123-456-789") + + mocker.patch.object(p.index_api, 'list_indexes', side_effect=[index_list_response]) + + response = p.list_indexes() + assert [i.name for i in response] == ["index1", "index2", "index3"] \ No newline at end of file From 468b754b5a74f5de37ebdb40745263fd1d9dfdb4 Mon Sep 17 00:00:00 2001 From: gdj0nes Date: Sun, 26 Nov 2023 16:47:17 -0500 Subject: [PATCH 18/39] Update the README.md to Spruce --- README.md | 129 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 74 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index bc9d90710..01e4bbb1a 100644 --- a/README.md +++ b/README.md @@ -28,20 +28,36 @@ pip3 install git+https://git@github.com/pinecone-io/pinecone-python-client.git@e pip3 install git+https://git@github.com/pinecone-io/pinecone-python-client.git@259deff ``` -## Creating an index +## Create a client +The following example creates an authenticated client. -The following example creates an index without a metadata -configuration. By default, Pinecone indexes all metadata. +```python +import os +from pinecone import Pinecone +pc = Pinecone(api_key=os.environ.get('PINECONE_API_KEY')) +``` +To use gRPC for interacting with an index, instantiate with `PineconeGRPC` ```python +import os +from pinecone.grpc import PineconeGRPC -import pinecone +pc = PineconeGRPC(api_key=os.environ.get('PINECONE_API_KEY')) +# Functionality matches non-gRPC client +index = pc.Index('index-name') +``` +## Create an index -pinecone.init(api_key="YOUR_API_KEY", - environment="us-west1-gcp") +The following example creates an index without a metadata +configuration. By default, Pinecone indexes all metadata. + +```python +from pinecone import Pinecone, PodSpec + +pc = Pinecone(api_key='<>') +pc.create_index("example-index", dimension=1536, metric="cosine", spec=PodSpec(environment='us-west-2', pod_type='p1.x1')) -pinecone.create_index("example-index", dimension=1024) ``` The following example creates an index that only indexes @@ -49,12 +65,18 @@ the "color" metadata field. Queries against this index cannot filter based on any other metadata field. ```python +from pinecone import Pinecone, PodSpec +pc = Pinecone(api_key='<>') + metadata_config = { "indexed": ["color"] } -pinecone.create_index("example-index-2", dimension=1024, - metadata_config=metadata_config) +pc.create_index( + "example-index-2", + dimension=1536, + spec=PodSpec(environment='us-west-2', pod_type='p1.x1', metadata_config=metadata_config) +) ``` ## List indexes @@ -62,11 +84,11 @@ pinecone.create_index("example-index-2", dimension=1024, The following example returns all indexes in your project. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") - -active_indexes = pinecone.list_indexes() +pc = Pinecone(api_key='<>') +for index in pc.list_indexes(): + print(index['name']) ``` ## Describe index @@ -74,12 +96,11 @@ active_indexes = pinecone.list_indexes() The following example returns information about the index `example-index`. ```python -import pinecone - -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +from pinecone import Pinecone -index_description = pinecone.describe_index("example-index") +pc = Pinecone(api_key='<>') +index_description = pc.describe_index("example-index") ``` ## Delete an index @@ -87,11 +108,11 @@ index_description = pinecone.describe_index("example-index") The following example deletes `example-index`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +pc = Pinecone(api_key='<>') -pinecone.delete_index("example-index") +pc.delete_index("example-index") ``` ## Scale replicas @@ -99,12 +120,12 @@ pinecone.delete_index("example-index") The following example changes the number of replicas for `example-index`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +pc = Pinecone(api_key='<>') new_number_of_replicas = 4 -pinecone.configure_index("example-index", replicas=new_number_of_replicas) +pc.configure_index("example-index", replicas=new_number_of_replicas) ``` ## Describe index statistics @@ -112,10 +133,10 @@ pinecone.configure_index("example-index", replicas=new_number_of_replicas) The following example returns statistics about the index `example-index`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") index_stats_response = index.describe_index_stats() ``` @@ -126,10 +147,10 @@ index_stats_response = index.describe_index_stats() The following example upserts vectors to `example-index`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") upsert_response = index.upsert( vectors=[ @@ -146,10 +167,10 @@ The following example queries the index `example-index` with metadata filtering. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") query_response = index.query( namespace="example-namespace", @@ -168,10 +189,10 @@ query_response = index.query( The following example deletes vectors by ID. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") delete_response = index.delete(ids=["vec1", "vec2"], namespace="example-namespace") ``` @@ -181,24 +202,23 @@ delete_response = index.delete(ids=["vec1", "vec2"], namespace="example-namespac The following example fetches vectors by ID. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") fetch_response = index.fetch(ids=["vec1", "vec2"], namespace="example-namespace") ``` - ## Update vectors The following example updates vectors by ID. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") -index = pinecone.Index("example-index") +pc = Pinecone(api_key='<>') +index = pc.Index("example-index") update_response = index.update( id="vec1", @@ -214,12 +234,11 @@ The following example creates the collection `example-collection` from `example-index`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", - environment="us-west1-gcp") +pc = Pinecone(api_key='<>') -pinecone.create_collection("example-collection", "example-index") +pc.create_collection("example-collection", "example-index") ``` ## List collections @@ -227,11 +246,11 @@ pinecone.create_collection("example-collection", "example-index") The following example returns a list of the collections in the current project. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +pc = Pinecone(api_key='<>') -active_collections = pinecone.list_collections() +active_collections = pc.list_collections() ``` ## Describe a collection @@ -240,11 +259,11 @@ The following example returns a description of the collection `example-collection`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +pc = Pinecone(api_key='<>') -collection_description = pinecone.describe_collection("example-collection") +collection_description = pc.describe_collection("example-collection") ``` ## Delete a collection @@ -252,11 +271,11 @@ collection_description = pinecone.describe_collection("example-collection") The following example deletes the collection `example-collection`. ```python -import pinecone +from pinecone import Pinecone -pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp") +pc = Pinecone(api_key='<>') -pinecone.delete_collection("example-collection") +pc.delete_collection("example-collection") ``` # Contributing From 8440197e61e5a5c6c0b8f727dbe18550282b982e Mon Sep 17 00:00:00 2001 From: Austin DeNoble Date: Sun, 26 Nov 2023 22:54:47 -0500 Subject: [PATCH 19/39] [spruce] Allow GRPCIndexBase to use config.host to establish endpoint (#248) ## Problem Currently, you cannot target an index using the `PineconeGRPC` client. `GRPCIndexBase._endpoint` is still trying to use `Config.PROJECT_NAME` and `Config.ENVIRONMENT` which have been deprecated. Screenshot 2023-11-26 at 9 20 49 PM ## Solution Update `GRPCIndexBase` to properly leverage the `config` which is passed via `PineconeGRPC`. We also need to strip out the `https://` and keep the port `443`. Screenshot 2023-11-26 at 9 50 36 PM ## Type of Change - [X] Bug fix (non-breaking change which fixes an issue) ## Test Plan --- pinecone/grpc/base.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/pinecone/grpc/base.py b/pinecone/grpc/base.py index 6b6ee641c..aca2223b9 100644 --- a/pinecone/grpc/base.py +++ b/pinecone/grpc/base.py @@ -18,6 +18,7 @@ _logger = logging.getLogger(__name__) + class GRPCIndexBase(ABC): """ Base class for grpc-based interaction with Pinecone indexes @@ -29,12 +30,13 @@ def __init__( self, index_name: str, config: Config, - channel: Optional[Channel] =None, + channel: Optional[Channel] = None, grpc_config: Optional[GRPCClientConfig] = None, _endpoint_override: Optional[str] = None, ): self.name = index_name + self.config = config self.grpc_client_config = grpc_config or GRPCClientConfig() self.retry_config = self.grpc_client_config.retry_config or RetryConfig() self.fixed_metadata = {"api-key": config.api_key, "service-name": index_name, "client-version": CLIENT_VERSION} @@ -76,11 +78,8 @@ def stub_class(self): pass def _endpoint(self): - return ( - self._endpoint_override - if self._endpoint_override - else f"{self.name}-{Config.PROJECT_NAME}.svc.{Config.ENVIRONMENT}.pinecone.io:443" - ) + grpcHost = self.config.host.replace("https://", "") + return self._endpoint_override if self._endpoint_override else f"{grpcHost}:443" def _gen_channel(self, options=None): target = self._endpoint() From f9ce05482c447e2932e28e4ae1ce85448a986914 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Sun, 26 Nov 2023 23:15:48 -0500 Subject: [PATCH 20/39] Update client with inlined type definitions under IndexModel and CreateIndexRequest (#249) ## Problem We want to keep the amount of generated cruft being pushed into peoples' faces to a minimum ## Solution We made some changes to our private openapi spec, then regenerated the core. Now fields such as name, dimension, and metric should be native python types. ## Usage ![Screenshot 2023-11-26 at 11 11 27 PM](https://github.com/pinecone-io/pinecone-python-client/assets/1326365/99b35b1f-4eaa-4922-b7cb-05f8afc98e5e) ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) --- pinecone/control/pinecone.py | 8 +- .../model/configure_index_request_spec_pod.py | 37 ++- .../core/client/model/create_index_request.py | 35 ++- pinecone/core/client/model/index_dimension.py | 288 ----------------- pinecone/core/client/model/index_metric.py | 289 ----------------- pinecone/core/client/model/index_model.py | 35 ++- pinecone/core/client/model/pod_spec.py | 68 +++- .../core/client/model/pod_spec_pod_type.py | 290 ------------------ .../core/client/model/pod_spec_replicas.py | 287 ----------------- pinecone/core/client/model/pod_spec_shards.py | 287 ----------------- pinecone/core/client/model/serverless_spec.py | 4 +- pinecone/core/client/models/__init__.py | 5 - tests/unit/test_control.py | 6 +- 13 files changed, 123 insertions(+), 1516 deletions(-) delete mode 100644 pinecone/core/client/model/index_dimension.py delete mode 100644 pinecone/core/client/model/index_metric.py delete mode 100644 pinecone/core/client/model/pod_spec_pod_type.py delete mode 100644 pinecone/core/client/model/pod_spec_replicas.py delete mode 100644 pinecone/core/client/model/pod_spec_shards.py diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 7091f6235..f39835d22 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -12,8 +12,6 @@ CreateCollectionRequest, CreateIndexRequest, ConfigureIndexRequest, - IndexMetric, - IndexDimension, ) from pinecone.models import ServerlessSpec, PodSpec, IndexList, CollectionList @@ -80,11 +78,11 @@ def create_index( api_instance = self.index_api if isinstance(spec, dict): - api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec)) + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec)) elif isinstance(spec, ServerlessSpec): - api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec.asdict())) + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec.asdict())) elif isinstance(spec, PodSpec): - api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=IndexDimension(dimension), metric=IndexMetric(metric), spec=spec.asdict())) + api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec.asdict())) def is_ready(): status = self._get_status(name) diff --git a/pinecone/core/client/model/configure_index_request_spec_pod.py b/pinecone/core/client/model/configure_index_request_spec_pod.py index fbfde79c1..809c21c9f 100644 --- a/pinecone/core/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/client/model/configure_index_request_spec_pod.py @@ -29,12 +29,6 @@ from pinecone.core.client.exceptions import ApiAttributeError -def lazy_import(): - from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType - from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas - globals()['PodSpecPodType'] = PodSpecPodType - globals()['PodSpecReplicas'] = PodSpecReplicas - class ConfigureIndexRequestSpecPod(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. @@ -61,9 +55,26 @@ class ConfigureIndexRequestSpecPod(ModelNormal): """ allowed_values = { + ('pod_type',): { + 'S1.X1': "s1.x1", + 'S1.X2': "s1.x2", + 'S1.X4': "s1.x4", + 'S1.X8': "s1.x8", + 'P1.X1': "p1.x1", + 'P1.X2': "p1.x2", + 'P1.X4': "p1.x4", + 'P1.X8': "p1.x8", + 'P2.X1': "p2.x1", + 'P2.X2': "p2.x2", + 'P2.X4': "p2.x4", + 'P2.X8': "p2.x8", + }, } validations = { + ('replicas',): { + 'inclusive_minimum': 1, + }, } @cached_property @@ -72,7 +83,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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -87,10 +97,9 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ - lazy_import() return { - 'replicas': (PodSpecReplicas,), # noqa: E501 - 'pod_type': (PodSpecPodType,), # noqa: E501 + 'replicas': (int,), # noqa: E501 + 'pod_type': (str,), # noqa: E501 } @cached_property @@ -144,8 +153,8 @@ 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,) - replicas (PodSpecReplicas): [optional] # noqa: E501 - pod_type (PodSpecPodType): [optional] # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -227,8 +236,8 @@ 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,) - replicas (PodSpecReplicas): [optional] # noqa: E501 - pod_type (PodSpecPodType): [optional] # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/create_index_request.py b/pinecone/core/client/model/create_index_request.py index d0fd33ce3..1bd0b2a83 100644 --- a/pinecone/core/client/model/create_index_request.py +++ b/pinecone/core/client/model/create_index_request.py @@ -29,12 +29,6 @@ from pinecone.core.client.exceptions import ApiAttributeError -def lazy_import(): - from pinecone.core.client.model.index_dimension import IndexDimension - from pinecone.core.client.model.index_metric import IndexMetric - globals()['IndexDimension'] = IndexDimension - globals()['IndexMetric'] = IndexMetric - class CreateIndexRequest(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. @@ -61,9 +55,18 @@ class CreateIndexRequest(ModelNormal): """ allowed_values = { + ('metric',): { + 'COSINE': "cosine", + 'EUCLIDEAN': "euclidean", + 'DOTPRODUCT': "dotproduct", + }, } validations = { + ('dimension',): { + 'inclusive_maximum': 20000, + 'inclusive_minimum': 1, + }, } @cached_property @@ -72,7 +75,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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -87,12 +89,11 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ - lazy_import() return { 'name': (str,), # noqa: E501 - 'dimension': (IndexDimension,), # noqa: E501 - 'metric': (IndexMetric,), # noqa: E501 - 'spec': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'metric': (str,), # noqa: E501 + 'spec': (dict,), # noqa: E501 } @cached_property @@ -119,9 +120,9 @@ def _from_openapi_data(cls, name, dimension, metric, spec, *args, **kwargs): # Args: name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. - dimension (IndexDimension): - metric (IndexMetric): - spec ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Spec objects describe how the index should be deployed + 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'. + spec (dict): Spec objects describe how the index should be deployed Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -210,9 +211,9 @@ def __init__(self, name, dimension, metric, spec, *args, **kwargs): # noqa: E50 Args: name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. - dimension (IndexDimension): - metric (IndexMetric): - spec ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Spec objects describe how the index should be deployed + 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'. + spec (dict): Spec objects describe how the index should be deployed Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/client/model/index_dimension.py b/pinecone/core/client/model/index_dimension.py deleted file mode 100644 index d6372eb12..000000000 --- a/pinecone/core/client/model/index_dimension.py +++ /dev/null @@ -1,288 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class IndexDimension(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',): { - '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), - } - - @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): - """IndexDimension - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The dimensions of the vectors to be inserted in the index. # noqa: E501 - - Keyword Args: - value (int): The dimensions of the vectors to be inserted in the index. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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): - """IndexDimension - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The dimensions of the vectors to be inserted in the index. # noqa: E501 - - Keyword Args: - value (int): The dimensions of the vectors to be inserted in the index. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/index_metric.py b/pinecone/core/client/model/index_metric.py deleted file mode 100644 index 989d34f0c..000000000 --- a/pinecone/core/client/model/index_metric.py +++ /dev/null @@ -1,289 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class IndexMetric(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - ('value',): { - '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (str,), - } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IndexMetric - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - - Keyword Args: - value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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): - """IndexMetric - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - - Keyword Args: - value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.., must be one of ["cosine", "euclidean", "dotproduct", ] # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/index_model.py b/pinecone/core/client/model/index_model.py index eb3eeab5f..d7f46e91c 100644 --- a/pinecone/core/client/model/index_model.py +++ b/pinecone/core/client/model/index_model.py @@ -30,12 +30,8 @@ def lazy_import(): - from pinecone.core.client.model.index_dimension import IndexDimension - from pinecone.core.client.model.index_metric import IndexMetric from pinecone.core.client.model.index_model_spec import IndexModelSpec from pinecone.core.client.model.index_model_status import IndexModelStatus - globals()['IndexDimension'] = IndexDimension - globals()['IndexMetric'] = IndexMetric globals()['IndexModelSpec'] = IndexModelSpec globals()['IndexModelStatus'] = IndexModelStatus @@ -65,9 +61,18 @@ class IndexModel(ModelNormal): """ allowed_values = { + ('metric',): { + 'COSINE': "cosine", + 'EUCLIDEAN': "euclidean", + 'DOTPRODUCT': "dotproduct", + }, } validations = { + ('dimension',): { + 'inclusive_maximum': 20000, + 'inclusive_minimum': 1, + }, } @cached_property @@ -94,8 +99,9 @@ def openapi_types(): lazy_import() return { 'name': (str,), # noqa: E501 - 'dimension': (IndexDimension,), # noqa: E501 - 'metric': (IndexMetric,), # noqa: E501 + 'dimension': (int,), # noqa: E501 + 'metric': (str,), # noqa: E501 + 'host': (str,), # noqa: E501 'spec': (IndexModelSpec,), # noqa: E501 'status': (IndexModelStatus,), # noqa: E501 } @@ -109,6 +115,7 @@ def discriminator(): 'name': 'name', # noqa: E501 'dimension': 'dimension', # noqa: E501 'metric': 'metric', # noqa: E501 + 'host': 'host', # noqa: E501 'spec': 'spec', # noqa: E501 'status': 'status', # noqa: E501 } @@ -120,13 +127,14 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, metric, spec, status, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. - dimension (IndexDimension): - metric (IndexMetric): + 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'. + host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): @@ -191,6 +199,7 @@ def _from_openapi_data(cls, name, dimension, metric, spec, status, *args, **kwar self.name = name self.dimension = dimension self.metric = metric + self.host = host self.spec = spec self.status = status for var_name, var_value in kwargs.items(): @@ -213,13 +222,14 @@ def _from_openapi_data(cls, name, dimension, metric, spec, status, *args, **kwar ]) @convert_js_args_to_python_args - def __init__(self, name, dimension, metric, spec, status, *args, **kwargs): # noqa: E501 + def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: name (str): The name of the index. The maximum length is 45 characters. It may contain lowercase alphanumeric characters or hyphens, and must not begin or end with a hyphen. - dimension (IndexDimension): - metric (IndexMetric): + 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'. + host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): @@ -282,6 +292,7 @@ def __init__(self, name, dimension, metric, spec, status, *args, **kwargs): # n self.name = name self.dimension = dimension self.metric = metric + self.host = host self.spec = spec self.status = status for var_name, var_value in kwargs.items(): diff --git a/pinecone/core/client/model/pod_spec.py b/pinecone/core/client/model/pod_spec.py index bc54f1514..a8b89cbfe 100644 --- a/pinecone/core/client/model/pod_spec.py +++ b/pinecone/core/client/model/pod_spec.py @@ -31,13 +31,7 @@ def lazy_import(): from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig - from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType - from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas - from pinecone.core.client.model.pod_spec_shards import PodSpecShards globals()['PodSpecMetadataConfig'] = PodSpecMetadataConfig - globals()['PodSpecPodType'] = PodSpecPodType - globals()['PodSpecReplicas'] = PodSpecReplicas - globals()['PodSpecShards'] = PodSpecShards class PodSpec(ModelNormal): @@ -65,9 +59,29 @@ class PodSpec(ModelNormal): """ allowed_values = { + ('pod_type',): { + 'S1.X1': "s1.x1", + 'S1.X2': "s1.x2", + 'S1.X4': "s1.x4", + 'S1.X8': "s1.x8", + 'P1.X1': "p1.x1", + 'P1.X2': "p1.x2", + 'P1.X4': "p1.x4", + 'P1.X8': "p1.x8", + 'P2.X1': "p2.x1", + 'P2.X2': "p2.x2", + 'P2.X4': "p2.x4", + 'P2.X8': "p2.x8", + }, } validations = { + ('replicas',): { + 'inclusive_minimum': 1, + }, + ('shards',): { + 'inclusive_minimum': 1, + }, ('pods',): { 'inclusive_minimum': 1, }, @@ -97,11 +111,12 @@ def openapi_types(): lazy_import() return { 'environment': (str,), # noqa: E501 - 'replicas': (PodSpecReplicas,), # noqa: E501 - 'shards': (PodSpecShards,), # noqa: E501 - 'pod_type': (PodSpecPodType,), # noqa: E501 + 'replicas': (int,), # noqa: E501 + 'shards': (int,), # noqa: E501 + 'pod_type': (str,), # noqa: E501 'pods': (int,), # noqa: E501 'metadata_config': (PodSpecMetadataConfig,), # noqa: E501 + 'source_collection': (str,), # noqa: E501 } @cached_property @@ -116,6 +131,7 @@ def discriminator(): 'pod_type': 'pod_type', # noqa: E501 'pods': 'pods', # noqa: E501 'metadata_config': 'metadata_config', # noqa: E501 + 'source_collection': 'source_collection', # noqa: E501 } read_only_vars = { @@ -132,6 +148,10 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 environment (str): The environment where the index is hosted. Keyword Args: + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -162,13 +182,14 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (PodSpecReplicas): [optional] # noqa: E501 - shards (PodSpecShards): [optional] # noqa: E501 - pod_type (PodSpecPodType): [optional] # noqa: E501 - pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. [optional] # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 + source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ + replicas = kwargs.get('replicas', 1) + shards = kwargs.get('shards', 1) + pod_type = kwargs.get('pod_type', "p1.x1") + pods = kwargs.get('pods', 1) _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) @@ -195,6 +216,10 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment + self.replicas = replicas + self.shards = shards + self.pod_type = pod_type + self.pods = pods for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -222,6 +247,10 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 environment (str): The environment where the index is hosted. Keyword Args: + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -252,13 +281,14 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (PodSpecReplicas): [optional] # noqa: E501 - shards (PodSpecShards): [optional] # noqa: E501 - pod_type (PodSpecPodType): [optional] # noqa: E501 - pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. [optional] # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 + source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ + replicas = kwargs.get('replicas', 1) + shards = kwargs.get('shards', 1) + pod_type = kwargs.get('pod_type', "p1.x1") + pods = kwargs.get('pods', 1) _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) @@ -283,6 +313,10 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment + self.replicas = replicas + self.shards = shards + self.pod_type = pod_type + self.pods = pods for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ diff --git a/pinecone/core/client/model/pod_spec_pod_type.py b/pinecone/core/client/model/pod_spec_pod_type.py deleted file mode 100644 index 120642ee3..000000000 --- a/pinecone/core/client/model/pod_spec_pod_type.py +++ /dev/null @@ -1,290 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class PodSpecPodType(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - ('value',): { - 'S1.X1': "s1.x1", - 'S1.X2': "s1.x2", - 'S1.X4': "s1.x4", - 'S1.X8': "s1.x8", - 'P1.X1': "p1.x1", - 'P1.X2': "p1.x2", - 'P1.X4': "p1.x4", - 'P1.X8': "p1.x8", - 'P2.X1': "p2.x1", - 'P2.X2': "p2.x2", - 'P2.X4': "p2.x4", - 'P2.X8': "p2.x8", - }, - } - - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (str,), - } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """PodSpecPodType - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 - - Keyword Args: - value (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "p1.x1" - - _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 ApiTypeError( - "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 ApiTypeError( - "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): - """PodSpecPodType - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 - - Keyword Args: - value (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. if omitted defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "p1.x1" - - _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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/pod_spec_replicas.py b/pinecone/core/client/model/pod_spec_replicas.py deleted file mode 100644 index 44ab8f5ac..000000000 --- a/pinecone/core/client/model/pod_spec_replicas.py +++ /dev/null @@ -1,287 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class PodSpecReplicas(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',): { - '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), - } - - @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): - """PodSpecReplicas - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # noqa: E501 - - Keyword Args: - value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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): - """PodSpecReplicas - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # noqa: E501 - - Keyword Args: - value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/pod_spec_shards.py b/pinecone/core/client/model/pod_spec_shards.py deleted file mode 100644 index c434e207f..000000000 --- a/pinecone/core/client/model/pod_spec_shards.py +++ /dev/null @@ -1,287 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, - 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 ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError - - - -class PodSpecShards(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',): { - '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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), - } - - @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): - """PodSpecShards - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # noqa: E501 - - Keyword Args: - value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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): - """PodSpecShards - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # noqa: E501 - - Keyword Args: - value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. # 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 ApiTypeError( - "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 ApiTypeError( - "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 ApiTypeError( - "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/client/model/serverless_spec.py b/pinecone/core/client/model/serverless_spec.py index af9792912..1fd00c6d0 100644 --- a/pinecone/core/client/model/serverless_spec.py +++ b/pinecone/core/client/model/serverless_spec.py @@ -112,7 +112,7 @@ def _from_openapi_data(cls, cloud, region, *args, **kwargs): # noqa: E501 Args: 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. Different cloud providers have different regions available. + region (str): The region where you would like your index to be created. Different cloud providers have different regions available. See AwsRegions and GcpRegions for a list of available options. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -199,7 +199,7 @@ def __init__(self, cloud, region, *args, **kwargs): # noqa: E501 Args: 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. Different cloud providers have different regions available. + region (str): The region where you would like your index to be created. Different cloud providers have different regions available. See AwsRegions and GcpRegions for a list of available options. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/client/models/__init__.py b/pinecone/core/client/models/__init__.py index 8cb83d215..11efdc9de 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -24,18 +24,13 @@ from pinecone.core.client.model.error_response_error import ErrorResponseError from pinecone.core.client.model.fetch_response import FetchResponse from pinecone.core.client.model.gcp_regions import GcpRegions -from pinecone.core.client.model.index_dimension import IndexDimension from pinecone.core.client.model.index_list import IndexList -from pinecone.core.client.model.index_metric import IndexMetric from pinecone.core.client.model.index_model import IndexModel from pinecone.core.client.model.index_model_spec import IndexModelSpec from pinecone.core.client.model.index_model_status import IndexModelStatus from pinecone.core.client.model.namespace_summary import NamespaceSummary from pinecone.core.client.model.pod_spec import PodSpec from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig -from pinecone.core.client.model.pod_spec_pod_type import PodSpecPodType -from pinecone.core.client.model.pod_spec_replicas import PodSpecReplicas -from pinecone.core.client.model.pod_spec_shards import PodSpecShards from pinecone.core.client.model.protobuf_any import ProtobufAny from pinecone.core.client.model.protobuf_null_value import ProtobufNullValue from pinecone.core.client.model.query_request import QueryRequest diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 570cc96f4..6a1ab8180 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -6,9 +6,9 @@ @pytest.fixture def index_list_response(): return IndexList(indexes=[ - IndexModel(name="index1", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), - IndexModel(name="index2", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), - IndexModel(name="index3", dimension=10, metric="euclidean", status={"ready": True}, spec={}, _check_type=False), + IndexModel(name="index1", dimension=10, metric="euclidean", host="asdf", status={"ready": True}, spec={}, _check_type=False), + IndexModel(name="index2", dimension=10, metric="euclidean", host="asdf", status={"ready": True}, spec={}, _check_type=False), + IndexModel(name="index3", dimension=10, metric="euclidean", host="asdf", status={"ready": True}, spec={}, _check_type=False), ]) From 90120b1e522f729404fff8e95171cde5ea8b28fb Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 27 Nov 2023 05:46:41 -0500 Subject: [PATCH 21/39] [Spruce] Integration test fixes (#250) ## Problem Integration tests need updating ## Type of Change - [x] Infrastructure change (CI configs, etc) --- .github/workflows/testing.yaml | 8 ++- pinecone/__init__.py | 4 +- pinecone/control/pinecone.py | 2 + .../model/configure_index_request_spec_pod.py | 14 ----- pinecone/core/client/model/pod_spec.py | 18 +------ pinecone/core/client/rest.py | 2 +- tests/integration/conftest.py | 50 ++++++++++++----- .../test_create_index_api_errors.py | 40 +++++++------- ....py => test_create_index_sl_happy_path.py} | 0 .../integration/test_create_index_timeouts.py | 2 +- tests/integration/test_describe_index.py | 29 ++++++---- tests/integration/test_list_indexes.py | 21 ++++---- tests/integration/test_upsert.py | 53 +++++++++++++++++++ 13 files changed, 149 insertions(+), 94 deletions(-) rename tests/integration/{test_create_index_happy_path.py => test_create_index_sl_happy_path.py} (100%) create mode 100644 tests/integration/test_upsert.py diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 9279cacb1..fd822de5f 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -38,7 +38,9 @@ jobs: strategy: matrix: python-version: [3.8, 3.11] - pineconeEnv: ['prod', 'staging'] + pineconeEnv: + - prod + # - staging max-parallel: 1 fail-fast: false steps: @@ -58,8 +60,6 @@ jobs: env: PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - TEST_CAPACITY_MODE_1: ${{ secrets.TEST_CAPACITY_MODE_1 }} - TEST_CAPACITY_MODE_2: ${{ secrets.TEST_CAPACITY_MODE_2 }} GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.python-version}}" - name: Run integration tests (REST, staging) @@ -68,8 +68,6 @@ jobs: env: PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY_STAGING }} - TEST_CAPACITY_MODE_1: ${{ secrets.TEST_CAPACITY_MODE_1 }} - TEST_CAPACITY_MODE_2: ${{ secrets.TEST_CAPACITY_MODE_2 }} GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.python-version}}" units-grpc: diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 4ccf6d4f3..91d143916 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -6,4 +6,6 @@ from .control.pinecone import Pinecone from .data.index import * from .models import * -# from .core.client.models import * \ No newline at end of file +from .core.client.models import ( + IndexModel, +) \ No newline at end of file diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index f39835d22..7c53653fe 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -83,6 +83,8 @@ def create_index( api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec.asdict())) elif isinstance(spec, PodSpec): api_instance.create_index(create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec.asdict())) + else: + raise TypeError("spec must be of type dict, ServerlessSpec, or PodSpec") def is_ready(): status = self._get_status(name) diff --git a/pinecone/core/client/model/configure_index_request_spec_pod.py b/pinecone/core/client/model/configure_index_request_spec_pod.py index 809c21c9f..a11a43757 100644 --- a/pinecone/core/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/client/model/configure_index_request_spec_pod.py @@ -55,20 +55,6 @@ class ConfigureIndexRequestSpecPod(ModelNormal): """ allowed_values = { - ('pod_type',): { - 'S1.X1': "s1.x1", - 'S1.X2': "s1.x2", - 'S1.X4': "s1.x4", - 'S1.X8': "s1.x8", - 'P1.X1': "p1.x1", - 'P1.X2': "p1.x2", - 'P1.X4': "p1.x4", - 'P1.X8': "p1.x8", - 'P2.X1': "p2.x1", - 'P2.X2': "p2.x2", - 'P2.X4': "p2.x4", - 'P2.X8': "p2.x8", - }, } validations = { diff --git a/pinecone/core/client/model/pod_spec.py b/pinecone/core/client/model/pod_spec.py index a8b89cbfe..62d897214 100644 --- a/pinecone/core/client/model/pod_spec.py +++ b/pinecone/core/client/model/pod_spec.py @@ -59,20 +59,6 @@ class PodSpec(ModelNormal): """ allowed_values = { - ('pod_type',): { - 'S1.X1': "s1.x1", - 'S1.X2': "s1.x2", - 'S1.X4': "s1.x4", - 'S1.X8': "s1.x8", - 'P1.X1': "p1.x1", - 'P1.X2': "p1.x2", - 'P1.X4': "p1.x4", - 'P1.X8': "p1.x8", - 'P2.X1': "p2.x1", - 'P2.X2': "p2.x2", - 'P2.X4': "p2.x4", - 'P2.X8': "p2.x8", - }, } validations = { @@ -150,7 +136,7 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 Keyword Args: replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -249,7 +235,7 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 Keyword Args: replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 - pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1", must be one of ["s1.x1", "s1.x2", "s1.x4", "s1.x8", "p1.x1", "p1.x2", "p1.x4", "p1.x8", "p2.x1", "p2.x2", "p2.x4", "p2.x8", ] # noqa: E501 + pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index 7e041c58a..9a51bb9b4 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -45,7 +45,7 @@ def __init__(self, resp): def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() + return self.urllib3_response.headers def getheader(self, name, default=None): """Returns a given response header.""" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 09bfaba85..79b78419b 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,5 +1,7 @@ import pytest -from pinecone import Pinecone +import random +import time +from pinecone import Pinecone, NotFoundException, ApiException from .helpers.helpers import generate_index_name, get_environment_var @pytest.fixture() @@ -13,11 +15,11 @@ def environment(): @pytest.fixture() def create_sl_index_params(index_name): - spec = { + spec = {"serverless": { 'cloud': 'aws', - 'region': 'us-east1' - } - return dict(name=index_name, dimension=10, metric='cosine', spec=spec, timeout=-1) + 'region': 'us-west-2' + }} + return dict(name=index_name, dimension=10, metric='cosine', spec=spec) @pytest.fixture() def create_pod_index_params(index_name, environment): @@ -26,6 +28,10 @@ def create_pod_index_params(index_name, environment): } return dict(name=index_name, dimension=10, metric='cosine', spec=spec, timeout=-1) +@pytest.fixture() +def random_vector(): + return [random.uniform(0, 1) for _ in range(10)] + @pytest.fixture() def index_name(request): test_name = request.node.name @@ -33,36 +39,52 @@ def index_name(request): @pytest.fixture() def ready_sl_index(client, index_name, create_sl_index_params): - del create_sl_index_params['timeout'] + create_sl_index_params['timeout'] = None client.create_index(**create_sl_index_params) yield index_name client.delete_index(index_name, -1) @pytest.fixture() def notready_sl_index(client, index_name, create_sl_index_params): - client.create_index(**create_sl_index_params) + client.create_index(**create_sl_index_params, timeout=-1) yield index_name - client.delete_index(index_name, -1) @pytest.fixture() def ready_pod_index(client, index_name, create_pod_index_params): del create_pod_index_params['timeout'] client.create_index(**create_pod_index_params) yield index_name - client.delete_index(index_name, -1) @pytest.fixture() def notready_pod_index(client, index_name, create_pod_index_params): client.create_index(**create_pod_index_params) yield index_name - client.delete_index(index_name, -1) + +def delete_with_retry(client, index_name, retries=0, sleep_interval=5): + print('Deleting index ' + index_name + ', retry ' + str(retries) + ', next sleep interval ' + str(sleep_interval)) + try: + client.delete_index(index_name, -1) + except NotFoundException: + pass + except ApiException as e: + if e.error.code == 'PRECONDITON_FAILED': + if retries > 5: + raise 'Unable to delete index ' + index_name + time.sleep(sleep_interval) + delete_with_retry(client, index_name, retries + 1, sleep_interval * 2) + else: + print(e.__class__) + print(e) + raise 'Unable to delete index ' + index_name + except Exception as e: + print(e.__class__) + print(e) + raise 'Unable to delete index ' + index_name @pytest.fixture(autouse=True) def cleanup(client, index_name): yield - client.delete_index(index_name, -1) - try: client.delete_index(index_name, -1) except: @@ -73,8 +95,8 @@ def cleanup_all(): yield client = Pinecone() - for index in client.list_indexes().databases: + for index in client.list_indexes(): try: - client.delete_index(index.name, -1) + delete_with_retry(client, index.name) except: pass \ No newline at end of file diff --git a/tests/integration/test_create_index_api_errors.py b/tests/integration/test_create_index_api_errors.py index 1e7f56a7b..8eeb3f3db 100644 --- a/tests/integration/test_create_index_api_errors.py +++ b/tests/integration/test_create_index_api_errors.py @@ -1,31 +1,31 @@ import pytest -from pinecone import ApiException +from pinecone import ApiException, ApiValueError class TestCreateIndexApiErrorCases: - def test_create_index_with_invalid_name(self, client, create_index_params): - create_index_params['name'] = '-invalid-name' + def test_create_index_with_invalid_name(self, client, create_sl_index_params): + create_sl_index_params['name'] = '-invalid-name' with pytest.raises(ApiException): - client.create_index(**create_index_params) + client.create_index(**create_sl_index_params) - def test_create_index_invalid_metric(self, client, create_index_params): - create_index_params['metric'] = 'invalid' - with pytest.raises(ApiException): - client.create_index(**create_index_params) + def test_create_index_invalid_metric(self, client, create_sl_index_params): + create_sl_index_params['metric'] = 'invalid' + with pytest.raises(ApiValueError): + client.create_index(**create_sl_index_params) - def test_create_index_with_invalid_neg_dimension(self, client, create_index_params): - create_index_params['dimension'] = -1 - with pytest.raises(ApiException): - client.create_index(**create_index_params) + def test_create_index_with_invalid_neg_dimension(self, client, create_sl_index_params): + create_sl_index_params['dimension'] = -1 + with pytest.raises(ApiValueError): + client.create_index(**create_sl_index_params) - def test_create_index_that_already_exists(self, client, create_index_params): - client.create_index(**create_index_params) + def test_create_index_that_already_exists(self, client, create_sl_index_params): + client.create_index(**create_sl_index_params) with pytest.raises(ApiException): - client.create_index(**create_index_params) + client.create_index(**create_sl_index_params) @pytest.mark.skip(reason='Bug filed https://app.asana.com/0/1205078872348810/1205917627868143') - def test_create_index_w_incompatible_options(self, client, create_index_params): - create_index_params['pod_type'] = 'p1.x2' - create_index_params['environment'] = 'us-east1-gcp' - create_index_params['replicas'] = 2 + def test_create_index_w_incompatible_options(self, client, create_sl_index_params): + create_sl_index_params['pod_type'] = 'p1.x2' + create_sl_index_params['environment'] = 'us-east1-gcp' + create_sl_index_params['replicas'] = 2 with pytest.raises(ApiException): - client.create_index(**create_index_params) \ No newline at end of file + client.create_index(**create_sl_index_params) \ No newline at end of file diff --git a/tests/integration/test_create_index_happy_path.py b/tests/integration/test_create_index_sl_happy_path.py similarity index 100% rename from tests/integration/test_create_index_happy_path.py rename to tests/integration/test_create_index_sl_happy_path.py diff --git a/tests/integration/test_create_index_timeouts.py b/tests/integration/test_create_index_timeouts.py index e9d5b4137..cb7e3ba5c 100644 --- a/tests/integration/test_create_index_timeouts.py +++ b/tests/integration/test_create_index_timeouts.py @@ -2,7 +2,7 @@ class TestCreateIndexWithTimeout: def test_create_index_default_timeout(self, client, create_sl_index_params): - del create_sl_index_params['timeout'] + create_sl_index_params['timeout'] = None client.create_index(**create_sl_index_params) # Waits infinitely for index to be ready desc = client.describe_index(create_sl_index_params['name']) diff --git a/tests/integration/test_describe_index.py b/tests/integration/test_describe_index.py index 0e1cecb36..90c96bf3e 100644 --- a/tests/integration/test_describe_index.py +++ b/tests/integration/test_describe_index.py @@ -1,30 +1,37 @@ import pytest -from pinecone import IndexDescription +from pinecone import IndexModel class TestDescribeIndex: def test_describe_index_when_ready(self, client, ready_sl_index, create_sl_index_params): description = client.describe_index(ready_sl_index) - assert type(description) == IndexDescription + + assert type(description) == IndexModel assert description.name == ready_sl_index assert description.dimension == create_sl_index_params['dimension'] assert description.metric == create_sl_index_params['metric'] - assert description.capacity_mode == create_sl_index_params['capacity_mode'] + assert description.spec.serverless['cloud'] == create_sl_index_params['spec']['serverless']['cloud'] + assert description.spec.serverless['region'] == create_sl_index_params['spec']['serverless']['region'] + + assert type(description.host) == str + assert description.host != "" + assert ready_sl_index in description.host - assert type(description.status.host) == str - assert description.status.host != "" assert description.status.state == 'Ready' - assert ready_sl_index in description.status.host assert description.status.ready == True def test_describe_index_when_not_ready(self, client, notready_sl_index, create_sl_index_params): description = client.describe_index(notready_sl_index) - assert type(description) == IndexDescription + assert type(description) == IndexModel assert description.name == notready_sl_index assert description.dimension == create_sl_index_params['dimension'] assert description.metric == create_sl_index_params['metric'] + assert description.spec.serverless['cloud'] == create_sl_index_params['spec']['serverless']['cloud'] + assert description.spec.serverless['region'] == create_sl_index_params['spec']['serverless']['region'] + + assert type(description.host) == str + assert description.host != "" + assert notready_sl_index in description.host - assert type(description.status.host) == str - assert description.status.host != "" - assert notready_sl_index in description.status.host - assert description.status.ready == False \ No newline at end of file + assert description.status.ready == False + assert description.status.state in ['Ready', 'Initializing'] \ No newline at end of file diff --git a/tests/integration/test_list_indexes.py b/tests/integration/test_list_indexes.py index 66fa39e19..e3d7ae83c 100644 --- a/tests/integration/test_list_indexes.py +++ b/tests/integration/test_list_indexes.py @@ -1,23 +1,22 @@ from pinecone import IndexModel class TestListIndexes(): - def test_list_indexes_includes_ready_indexes(self, client, ready_index, create_index_params): + def test_list_indexes_includes_ready_indexes(self, client, ready_sl_index, create_sl_index_params): list_response = client.list_indexes() assert len(list_response.indexes) != 0 assert type(list_response.indexes[0]) == IndexModel - created_index = [index for index in list_response.indexes if index.name == ready_index][0] - assert created_index.name == ready_index - assert created_index.dimension == create_index_params['dimension'] - assert created_index.metric == create_index_params['metric'] - assert ready_index in created_index.host - assert created_index.capacity_mode == create_index_params['capacity_mode'] + created_index = [index for index in list_response.indexes if index.name == ready_sl_index][0] + assert created_index.name == ready_sl_index + assert created_index.dimension == create_sl_index_params['dimension'] + assert created_index.metric == create_sl_index_params['metric'] + assert ready_sl_index in created_index.host - def test_list_indexes_includes_not_ready_indexes(self, client, notready_index): + def test_list_indexes_includes_not_ready_indexes(self, client, notready_sl_index): list_response = client.list_indexes() assert len(list_response.indexes) != 0 assert type(list_response.indexes[0]) == IndexModel - created_index = [index for index in list_response.indexes if index.name == notready_index][0] - assert created_index.name == notready_index - assert notready_index in created_index.name + created_index = [index for index in list_response.indexes if index.name == notready_sl_index][0] + assert created_index.name == notready_sl_index + assert notready_sl_index in created_index.name diff --git a/tests/integration/test_upsert.py b/tests/integration/test_upsert.py new file mode 100644 index 000000000..91aa90bdd --- /dev/null +++ b/tests/integration/test_upsert.py @@ -0,0 +1,53 @@ +import pytest +from pinecone import Vector, SparseValues + +class TestUpsert: + def test_upsert_sanity(self, client, ready_sl_index, random_vector): + idx = client.Index(ready_sl_index) + + # Tuples + idx.upsert(vectors=[('1', random_vector), ('2', random_vector), ('3', random_vector)]) + + # Tuples with metadata + idx.upsert(vectors=[('4', random_vector, {'key': 'value'}), ('5', random_vector, {'key': 'value2'})]) + + # Vector objects + idx.upsert(vectors=[Vector(id='6', values=random_vector)]) + idx.upsert(vectors=[Vector(id='7', values=random_vector, metadata={'key': 'value'})]) + + # Dict + idx.upsert(vectors=[{'id': '8', 'values': random_vector}]) + + # Dict with metadata + idx.upsert(vectors=[{'id': '8', 'values': random_vector, 'metadata': {'key': 'value'}}]) + + idx.describe_index_stats() + + def test_upsert_sparse_vectors(self, client, random_vector, create_sl_index_params, index_name): + create_sl_index_params['metric'] = 'dotproduct' + create_sl_index_params['timeout'] = 300 + client.create_index(**create_sl_index_params) + + idx = client.Index(index_name) + idx.upsert(vectors=[Vector(id='1', values=random_vector, sparse_values=SparseValues(values=[0.1, 0.2, 0.3], indices=[1, 2, 3]))]) + idx.upsert(vectors=[{'id': '8', 'values': random_vector, 'metadata': {'key': 'value'}, 'sparse_values': {'values': [0.1, 0.2, 0.3], 'indices': [1, 2, 3] }}]) + + def test_upsert_with_invalid_vector(self, client, ready_sl_index, random_vector): + idx = client.Index(ready_sl_index) + + with pytest.raises(TypeError): + # non-vector + idx.upsert(vectors=[('1', 'invalid_vector')]) + + with pytest.raises(TypeError): + # bogus metadata + idx.upsert(vectors=[('1', random_vector, 'invalid_metadata')]) + + with pytest.raises(TypeError): + # non-string id + idx.upsert(vectors=[(1, random_vector)]) + + with pytest.raises(TypeError): + idx.upsert(vectors=[{'id': 1, 'values': random_vector}]) + + \ No newline at end of file From 203a0df5a13b73e76cf47e458507603fef8a7d0f Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Wed, 29 Nov 2023 22:48:22 -0500 Subject: [PATCH 22/39] [spruce] Add names() helper method on list results (#252) ## Problem I'd like to make it even simpler to iterate over index names. ## Solution With this change, you can now ```python from pinecone import Pinecone pc = Pinecone(api_key='xxx') for name in pc.list_indexes().names(): # do something ``` ## Type of Change - [x] New feature (non-breaking change which adds functionality) ## Test Plan Unit test added. --- pinecone/control/pinecone.py | 2 +- pinecone/models/index_list.py | 3 +++ tests/unit/models/test_index_list.py | 8 +++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 7c53653fe..93ec66ab2 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -123,7 +123,7 @@ def delete_index(self, name: str, timeout: Optional[int] = None): self.index_host_store.delete_host(self.config, name) def get_remaining(): - return name in api_instance.list_indexes() + return name in api_instance.list_indexes().names() if timeout == -1: return diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py index ed1974f5c..d5454c2be 100644 --- a/pinecone/models/index_list.py +++ b/pinecone/models/index_list.py @@ -5,6 +5,9 @@ def __init__(self, index_list: OpenAPIIndexList): self.index_list = index_list self.current = 0 + def names(self): + return [i['name'] for i in self.index_list.indexes] + def __getitem__(self, key): return self.index_list.indexes[key] diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py index fe34b738f..d28f472ca 100644 --- a/tests/unit/models/test_index_list.py +++ b/tests/unit/models/test_index_list.py @@ -22,7 +22,7 @@ def index_list_response(): }, { "name": "test-index-2", - "dimension": 2, + "dimension": 3, "metric": "cosine", "spec": { "serverless": { @@ -41,6 +41,12 @@ def test_index_list_has_length(self, index_list_response): def test_index_list_is(self, index_list_response): iil = IndexList(index_list_response) assert [i['name'] for i in iil] == ['test-index-1', 'test-index-2'] + assert [i['dimension'] for i in iil] == [2, 3] + assert [i['metric'] for i in iil] == ['cosine', 'cosine'] + + def test_index_list_names_syntactic_sugar(self, index_list_response): + iil = IndexList(index_list_response) + assert iil.names() == ['test-index-1', 'test-index-2'] def test_index_list_getitem(self, index_list_response): iil = IndexList(index_list_response) From 1318537071569d27f141b3788ba4b76239ad0d7c Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 1 Dec 2023 14:36:19 -0500 Subject: [PATCH 23/39] Cleanup exception hierarchy (#251) ## Problem We want to create a base exception `PineconeException` that all other errors extend to simplify error handling. ## Solution These changes are mainly derived from updated openapi templates. New exception hierarchy is: - PineconeException - PineconeConfigurationError - PineconeApiException - NotFoundException - ForbiddenException - ...etc - PineconeProtocolError (GRPC) Almost all find-and-replace changes except some tiny modifications in `pinecone/exceptions.py` to extend a different type with the same name in order for all types to share a common base type coming from the generated code. Not much to see here. ## Type of Change - [x] Breaking change (fix or feature that would cause existing functionality to not work as expected) --- pinecone/config/config.py | 1 - pinecone/control/index_host_store.py | 3 +- pinecone/core/client/__init__.py | 12 +-- pinecone/core/client/api_client.py | 22 ++--- pinecone/core/client/configuration.py | 4 +- pinecone/core/client/exceptions.py | 30 +++---- pinecone/core/client/model/aws_regions.py | 16 ++-- pinecone/core/client/model/collection_list.py | 10 +-- .../core/client/model/collection_model.py | 10 +-- .../client/model/configure_index_request.py | 10 +-- .../model/configure_index_request_spec.py | 10 +-- .../model/configure_index_request_spec_pod.py | 10 +-- .../client/model/create_collection_request.py | 10 +-- .../core/client/model/create_index_request.py | 10 +-- pinecone/core/client/model/delete_request.py | 10 +-- .../model/describe_index_stats_request.py | 10 +-- .../model/describe_index_stats_response.py | 10 +-- pinecone/core/client/model/error_response.py | 10 +-- .../core/client/model/error_response_error.py | 10 +-- pinecone/core/client/model/fetch_response.py | 10 +-- pinecone/core/client/model/gcp_regions.py | 16 ++-- pinecone/core/client/model/index_list.py | 10 +-- pinecone/core/client/model/index_model.py | 10 +-- .../core/client/model/index_model_spec.py | 10 +-- .../core/client/model/index_model_status.py | 10 +-- .../core/client/model/namespace_summary.py | 10 +-- pinecone/core/client/model/pod_spec.py | 10 +-- .../client/model/pod_spec_metadata_config.py | 10 +-- pinecone/core/client/model/protobuf_any.py | 10 +-- .../core/client/model/protobuf_null_value.py | 12 +-- pinecone/core/client/model/query_request.py | 10 +-- pinecone/core/client/model/query_response.py | 10 +-- pinecone/core/client/model/query_vector.py | 10 +-- pinecone/core/client/model/rpc_status.py | 10 +-- pinecone/core/client/model/scored_vector.py | 10 +-- pinecone/core/client/model/serverless_spec.py | 10 +-- .../core/client/model/single_query_results.py | 10 +-- pinecone/core/client/model/sparse_values.py | 10 +-- pinecone/core/client/model/update_request.py | 10 +-- pinecone/core/client/model/upsert_request.py | 10 +-- pinecone/core/client/model/upsert_response.py | 10 +-- pinecone/core/client/model/vector.py | 10 +-- pinecone/core/client/model_utils.py | 84 +++++++++---------- pinecone/core/client/rest.py | 10 +-- pinecone/exceptions.py | 28 +++---- tests/integ/test_index.py | 6 +- tests/integration/conftest.py | 4 +- .../test_create_index_api_errors.py | 12 +-- .../test_create_index_type_errors.py | 4 +- tests/unit/test_config.py | 2 +- 50 files changed, 296 insertions(+), 300 deletions(-) diff --git a/pinecone/config/config.py b/pinecone/config/config.py index 2bd851419..92d7a7767 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -2,7 +2,6 @@ import os from pinecone.exceptions import PineconeConfigurationError -from pinecone.core.client.exceptions import ApiKeyError from pinecone.config.openapi import OpenApiConfigFactory from pinecone.core.client.configuration import Configuration as OpenApiConfiguration diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index d27bf12af..69e98bf91 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,6 +1,7 @@ from typing import Dict from pinecone.config import Config from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi +from pinecone.core.client.exceptions import PineconeException class SingletonMeta(type): _instances: Dict[str, str] = {} @@ -40,5 +41,5 @@ def get_host(self, api: IndexOperationsApi, config: Config, index_name: str) -> description = api.describe_index(index_name) self.set_host(config, index_name, description.host) if not self.key_exists(key): - raise Exception(f"Could not get host for index: {index_name}. Call describe_index('{index_name}') to check the current status.") + raise PineconeException(f"Could not get host for index: {index_name}. Call describe_index('{index_name}') to check the current status.") return self._indexHosts[key] diff --git a/pinecone/core/client/__init__.py b/pinecone/core/client/__init__.py index 486f91455..0746e0651 100644 --- a/pinecone/core/client/__init__.py +++ b/pinecone/core/client/__init__.py @@ -19,9 +19,9 @@ from pinecone.core.client.configuration import Configuration # import exceptions -from pinecone.core.client.exceptions import OpenApiException -from pinecone.core.client.exceptions import ApiAttributeError -from pinecone.core.client.exceptions import ApiTypeError -from pinecone.core.client.exceptions import ApiValueError -from pinecone.core.client.exceptions import ApiKeyError -from pinecone.core.client.exceptions import ApiException +from pinecone.core.client.exceptions import PineconeException +from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.client.exceptions import PineconeApiTypeError +from pinecone.core.client.exceptions import PineconeApiValueError +from pinecone.core.client.exceptions import PineconeApiKeyError +from pinecone.core.client.exceptions import PineconeApiException diff --git a/pinecone/core/client/api_client.py b/pinecone/core/client/api_client.py index 88cb5182d..e7e2feae5 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/client/api_client.py @@ -22,7 +22,7 @@ from pinecone.core.client import rest from pinecone.core.client.configuration import Configuration -from pinecone.core.client.exceptions import ApiTypeError, ApiValueError, ApiException +from pinecone.core.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException from pinecone.core.client.model_utils import ( ModelNormal, ModelSimple, @@ -197,7 +197,7 @@ def __call_api( post_params=post_params, body=body, _preload_content=_preload_content, _request_timeout=_request_timeout) - except ApiException as e: + except PineconeApiException as e: e.body = e.body.decode('utf-8') raise e @@ -284,7 +284,7 @@ def sanitize_for_serialization(cls, obj): return [cls.sanitize_for_serialization(item) for item in obj] if isinstance(obj, dict): return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} - raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) + raise PineconeApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) def deserialize(self, response, response_type, _check_type): """Deserializes response into an object. @@ -482,7 +482,7 @@ def request(self, method, url, query_params=None, headers=None, _request_timeout=_request_timeout, body=body) else: - raise ApiValueError( + raise PineconeApiValueError( "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) @@ -543,7 +543,7 @@ def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[i # if the file field is nullable, skip None values continue if file_instance.closed is True: - raise ApiValueError( + raise PineconeApiValueError( "Cannot read a closed file. The passed in file_type " "for %s must be open." % param_name ) @@ -614,7 +614,7 @@ def update_params_for_auth(self, headers, querys, auth_settings, elif auth_setting['in'] == 'query': querys.append((auth_setting['key'], auth_setting['value'])) else: - raise ApiValueError( + raise PineconeApiValueError( 'Authentication token must be in `query` or `header`' ) @@ -784,7 +784,7 @@ def call_with_http_info(self, **kwargs): ) except IndexError: if self.settings['servers']: - raise ApiValueError( + raise PineconeApiValueError( "Invalid host index. Must be 0 <= index < %s" % len(self.settings['servers']) ) @@ -792,17 +792,17 @@ def call_with_http_info(self, **kwargs): for key, value in kwargs.items(): if key not in self.params_map['all']: - raise ApiTypeError( + raise PineconeApiTypeError( "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.settings['operation_id']) ) - # only throw this nullable ApiValueError if _check_input_type + # only throw this nullable PineconeApiValueError if _check_input_type # is False, if _check_input_type==True we catch this case # in self.__validate_inputs if (key not in self.params_map['nullable'] and value is None and kwargs['_check_input_type'] is False): - raise ApiValueError( + raise PineconeApiValueError( "Value may not be None for non-nullable parameter `%s`" " when calling `%s`" % (key, self.settings['operation_id']) @@ -810,7 +810,7 @@ def call_with_http_info(self, **kwargs): for key in self.params_map['required']: if key not in kwargs.keys(): - raise ApiValueError( + raise PineconeApiValueError( "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings['operation_id']) ) diff --git a/pinecone/core/client/configuration.py b/pinecone/core/client/configuration.py index 99447c9f2..a7ab0cd4c 100644 --- a/pinecone/core/client/configuration.py +++ b/pinecone/core/client/configuration.py @@ -15,7 +15,7 @@ import urllib3 from http import client as http_client -from pinecone.core.client.exceptions import ApiValueError +from pinecone.core.client.exceptions import PineconeApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { @@ -234,7 +234,7 @@ def __setattr__(self, name, value): s = set(filter(None, value.split(','))) for v in s: if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: - raise ApiValueError( + raise PineconeApiValueError( "Invalid keyword: '{0}''".format(v)) self._disabled_client_side_validations = s diff --git a/pinecone/core/client/exceptions.py b/pinecone/core/client/exceptions.py index 3d1ff935a..665dada66 100644 --- a/pinecone/core/client/exceptions.py +++ b/pinecone/core/client/exceptions.py @@ -9,11 +9,11 @@ -class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" +class PineconeException(Exception): + """The base exception class for all exceptions in the Pinecone Python SDK""" -class ApiTypeError(OpenApiException, TypeError): +class PineconeApiTypeError(PineconeException, TypeError): def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): """ Raises an exception for TypeErrors @@ -39,10 +39,10 @@ def __init__(self, msg, path_to_item=None, valid_classes=None, full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) + super(PineconeApiTypeError, self).__init__(full_msg) -class ApiValueError(OpenApiException, ValueError): +class PineconeApiValueError(PineconeException, ValueError): def __init__(self, msg, path_to_item=None): """ Args: @@ -57,10 +57,10 @@ def __init__(self, msg, path_to_item=None): full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) + super(PineconeApiValueError, self).__init__(full_msg) -class ApiAttributeError(OpenApiException, AttributeError): +class PineconeApiAttributeError(PineconeException, AttributeError): def __init__(self, msg, path_to_item=None): """ Raised when an attribute reference or assignment fails. @@ -76,10 +76,10 @@ def __init__(self, msg, path_to_item=None): full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiAttributeError, self).__init__(full_msg) + super(PineconeApiAttributeError, self).__init__(full_msg) -class ApiKeyError(OpenApiException, KeyError): +class PineconeApiKeyError(PineconeException, KeyError): def __init__(self, msg, path_to_item=None): """ Args: @@ -93,10 +93,10 @@ def __init__(self, msg, path_to_item=None): full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) + super(PineconeApiKeyError, self).__init__(full_msg) -class ApiException(OpenApiException): +class PineconeApiException(PineconeException): def __init__(self, status=None, reason=None, http_resp=None): if http_resp: @@ -124,25 +124,25 @@ def __str__(self): return error_message -class NotFoundException(ApiException): +class NotFoundException(PineconeApiException): def __init__(self, status=None, reason=None, http_resp=None): super(NotFoundException, self).__init__(status, reason, http_resp) -class UnauthorizedException(ApiException): +class UnauthorizedException(PineconeApiException): def __init__(self, status=None, reason=None, http_resp=None): super(UnauthorizedException, self).__init__(status, reason, http_resp) -class ForbiddenException(ApiException): +class ForbiddenException(PineconeApiException): def __init__(self, status=None, reason=None, http_resp=None): super(ForbiddenException, self).__init__(status, reason, http_resp) -class ServiceException(ApiException): +class ServiceException(PineconeApiException): def __init__(self, status=None, reason=None, http_resp=None): super(ServiceException, self).__init__(status, reason, http_resp) diff --git a/pinecone/core/client/model/aws_regions.py b/pinecone/core/client/model/aws_regions.py index 04848cb3f..09739bfea 100644 --- a/pinecone/core/client/model/aws_regions.py +++ b/pinecone/core/client/model/aws_regions.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -156,7 +156,7 @@ def __init__(self, *args, **kwargs): args = list(args) value = args.pop(0) else: - raise ApiTypeError( + 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__,), @@ -168,7 +168,7 @@ def __init__(self, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -185,7 +185,7 @@ def __init__(self, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, @@ -248,7 +248,7 @@ def _from_openapi_data(cls, *args, **kwargs): args = list(args) value = args.pop(0) else: - raise ApiTypeError( + 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__,), @@ -260,7 +260,7 @@ def _from_openapi_data(cls, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -277,7 +277,7 @@ def _from_openapi_data(cls, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, diff --git a/pinecone/core/client/model/collection_list.py b/pinecone/core/client/model/collection_list.py index 2cac53b57..1317d964c 100644 --- a/pinecone/core/client/model/collection_list.py +++ b/pinecone/core/client/model/collection_list.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -152,7 +152,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -232,7 +232,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -257,5 +257,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/collection_model.py b/pinecone/core/client/model/collection_model.py index acbcaf952..4e9d54280 100644 --- a/pinecone/core/client/model/collection_model.py +++ b/pinecone/core/client/model/collection_model.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -172,7 +172,7 @@ def _from_openapi_data(cls, name, size, status, dimension, record_count, *args, self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -264,7 +264,7 @@ def __init__(self, name, size, status, dimension, record_count, *args, **kwargs) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -294,5 +294,5 @@ def __init__(self, name, size, status, dimension, record_count, *args, **kwargs) continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/configure_index_request.py b/pinecone/core/client/model/configure_index_request.py index 864c1427b..0cf62d638 100644 --- a/pinecone/core/client/model/configure_index_request.py +++ b/pinecone/core/client/model/configure_index_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -154,7 +154,7 @@ def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -237,7 +237,7 @@ def __init__(self, spec, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -263,5 +263,5 @@ def __init__(self, spec, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/configure_index_request_spec.py b/pinecone/core/client/model/configure_index_request_spec.py index e673d077f..151a9955d 100644 --- a/pinecone/core/client/model/configure_index_request_spec.py +++ b/pinecone/core/client/model/configure_index_request_spec.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -154,7 +154,7 @@ def _from_openapi_data(cls, pod, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -237,7 +237,7 @@ def __init__(self, pod, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -263,5 +263,5 @@ def __init__(self, pod, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/configure_index_request_spec_pod.py b/pinecone/core/client/model/configure_index_request_spec_pod.py index a11a43757..8a8adab60 100644 --- a/pinecone/core/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/client/model/configure_index_request_spec_pod.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -152,7 +152,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -233,7 +233,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -258,5 +258,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/create_collection_request.py b/pinecone/core/client/model/create_collection_request.py index c80103ae1..30f9041f2 100644 --- a/pinecone/core/client/model/create_collection_request.py +++ b/pinecone/core/client/model/create_collection_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -151,7 +151,7 @@ def _from_openapi_data(cls, name, source, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -236,7 +236,7 @@ def __init__(self, name, source, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -263,5 +263,5 @@ def __init__(self, name, source, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/create_index_request.py b/pinecone/core/client/model/create_index_request.py index 1bd0b2a83..e362ad43d 100644 --- a/pinecone/core/client/model/create_index_request.py +++ b/pinecone/core/client/model/create_index_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -166,7 +166,7 @@ def _from_openapi_data(cls, name, dimension, metric, spec, *args, **kwargs): # self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -255,7 +255,7 @@ def __init__(self, name, dimension, metric, spec, *args, **kwargs): # noqa: E50 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -284,5 +284,5 @@ def __init__(self, name, dimension, metric, spec, *args, **kwargs): # noqa: E50 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/delete_request.py b/pinecone/core/client/model/delete_request.py index 10e0832b3..260871be3 100644 --- a/pinecone/core/client/model/delete_request.py +++ b/pinecone/core/client/model/delete_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -157,7 +157,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -240,7 +240,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -265,5 +265,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/describe_index_stats_request.py b/pinecone/core/client/model/describe_index_stats_request.py index a6f8de18d..388f9c026 100644 --- a/pinecone/core/client/model/describe_index_stats_request.py +++ b/pinecone/core/client/model/describe_index_stats_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -146,7 +146,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -226,7 +226,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -251,5 +251,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/describe_index_stats_response.py b/pinecone/core/client/model/describe_index_stats_response.py index e56c1ab87..e04ef7e69 100644 --- a/pinecone/core/client/model/describe_index_stats_response.py +++ b/pinecone/core/client/model/describe_index_stats_response.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -161,7 +161,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -244,7 +244,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -269,5 +269,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/error_response.py b/pinecone/core/client/model/error_response.py index 543305804..967176dbf 100644 --- a/pinecone/core/client/model/error_response.py +++ b/pinecone/core/client/model/error_response.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -157,7 +157,7 @@ def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -242,7 +242,7 @@ def __init__(self, status, error, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -269,5 +269,5 @@ def __init__(self, status, error, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/error_response_error.py b/pinecone/core/client/model/error_response_error.py index 4edd409ff..444fa2afe 100644 --- a/pinecone/core/client/model/error_response_error.py +++ b/pinecone/core/client/model/error_response_error.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -174,7 +174,7 @@ def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -260,7 +260,7 @@ def __init__(self, code, message, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -287,5 +287,5 @@ def __init__(self, code, message, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/fetch_response.py b/pinecone/core/client/model/fetch_response.py index 64d0f1ab6..a142ed42c 100644 --- a/pinecone/core/client/model/fetch_response.py +++ b/pinecone/core/client/model/fetch_response.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -155,7 +155,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -236,7 +236,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -261,5 +261,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/gcp_regions.py b/pinecone/core/client/model/gcp_regions.py index 8ed733971..e7713bd81 100644 --- a/pinecone/core/client/model/gcp_regions.py +++ b/pinecone/core/client/model/gcp_regions.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -159,7 +159,7 @@ def __init__(self, *args, **kwargs): args = list(args) value = args.pop(0) else: - raise ApiTypeError( + 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__,), @@ -171,7 +171,7 @@ def __init__(self, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -188,7 +188,7 @@ def __init__(self, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, @@ -251,7 +251,7 @@ def _from_openapi_data(cls, *args, **kwargs): args = list(args) value = args.pop(0) else: - raise ApiTypeError( + 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__,), @@ -263,7 +263,7 @@ def _from_openapi_data(cls, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -280,7 +280,7 @@ def _from_openapi_data(cls, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, diff --git a/pinecone/core/client/model/index_list.py b/pinecone/core/client/model/index_list.py index a75628d53..fef0fb381 100644 --- a/pinecone/core/client/model/index_list.py +++ b/pinecone/core/client/model/index_list.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -152,7 +152,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -232,7 +232,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -257,5 +257,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/index_model.py b/pinecone/core/client/model/index_model.py index d7f46e91c..1910c7d31 100644 --- a/pinecone/core/client/model/index_model.py +++ b/pinecone/core/client/model/index_model.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -180,7 +180,7 @@ def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -273,7 +273,7 @@ def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -304,5 +304,5 @@ def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs) continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/index_model_spec.py b/pinecone/core/client/model/index_model_spec.py index 1a15d873f..959de0066 100644 --- a/pinecone/core/client/model/index_model_spec.py +++ b/pinecone/core/client/model/index_model_spec.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -157,7 +157,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -238,7 +238,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -263,5 +263,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/index_model_status.py b/pinecone/core/client/model/index_model_status.py index 7ec7ca4ee..58b2e3e85 100644 --- a/pinecone/core/client/model/index_model_status.py +++ b/pinecone/core/client/model/index_model_status.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -161,7 +161,7 @@ def _from_openapi_data(cls, ready, state, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -246,7 +246,7 @@ def __init__(self, ready, state, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -273,5 +273,5 @@ def __init__(self, ready, state, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/namespace_summary.py b/pinecone/core/client/model/namespace_summary.py index c42d8b5a7..0ea3fd96b 100644 --- a/pinecone/core/client/model/namespace_summary.py +++ b/pinecone/core/client/model/namespace_summary.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -146,7 +146,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -226,7 +226,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -251,5 +251,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/pod_spec.py b/pinecone/core/client/model/pod_spec.py index 62d897214..8e63cbc8b 100644 --- a/pinecone/core/client/model/pod_spec.py +++ b/pinecone/core/client/model/pod_spec.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -185,7 +185,7 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -282,7 +282,7 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -312,5 +312,5 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/pod_spec_metadata_config.py b/pinecone/core/client/model/pod_spec_metadata_config.py index b41a51f3f..8fe593d5d 100644 --- a/pinecone/core/client/model/pod_spec_metadata_config.py +++ b/pinecone/core/client/model/pod_spec_metadata_config.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -146,7 +146,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -226,7 +226,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -251,5 +251,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/protobuf_any.py b/pinecone/core/client/model/protobuf_any.py index fb46af753..c1bbf8c64 100644 --- a/pinecone/core/client/model/protobuf_any.py +++ b/pinecone/core/client/model/protobuf_any.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -149,7 +149,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -230,7 +230,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -255,5 +255,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/protobuf_null_value.py b/pinecone/core/client/model/protobuf_null_value.py index 83e635111..f38ae2ca8 100644 --- a/pinecone/core/client/model/protobuf_null_value.py +++ b/pinecone/core/client/model/protobuf_null_value.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -162,7 +162,7 @@ def __init__(self, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -179,7 +179,7 @@ def __init__(self, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, @@ -250,7 +250,7 @@ def _from_openapi_data(cls, *args, **kwargs): _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -267,7 +267,7 @@ def _from_openapi_data(cls, *args, **kwargs): self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.value = value if kwargs: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, diff --git a/pinecone/core/client/model/query_request.py b/pinecone/core/client/model/query_request.py index e5a209480..0fe0779aa 100644 --- a/pinecone/core/client/model/query_request.py +++ b/pinecone/core/client/model/query_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -191,7 +191,7 @@ def _from_openapi_data(cls, top_k, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -282,7 +282,7 @@ def __init__(self, top_k, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -308,5 +308,5 @@ def __init__(self, top_k, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/query_response.py b/pinecone/core/client/model/query_response.py index 49e28d999..5f932cc43 100644 --- a/pinecone/core/client/model/query_response.py +++ b/pinecone/core/client/model/query_response.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -160,7 +160,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -242,7 +242,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -267,5 +267,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/query_vector.py b/pinecone/core/client/model/query_vector.py index 62c5bb713..68784ec14 100644 --- a/pinecone/core/client/model/query_vector.py +++ b/pinecone/core/client/model/query_vector.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -172,7 +172,7 @@ def _from_openapi_data(cls, values, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -259,7 +259,7 @@ def __init__(self, values, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -285,5 +285,5 @@ def __init__(self, values, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/rpc_status.py b/pinecone/core/client/model/rpc_status.py index aa3f851e9..ebcfb2c28 100644 --- a/pinecone/core/client/model/rpc_status.py +++ b/pinecone/core/client/model/rpc_status.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -158,7 +158,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -240,7 +240,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -265,5 +265,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/scored_vector.py b/pinecone/core/client/model/scored_vector.py index 69828a242..b8681f645 100644 --- a/pinecone/core/client/model/scored_vector.py +++ b/pinecone/core/client/model/scored_vector.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -170,7 +170,7 @@ def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -257,7 +257,7 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -283,5 +283,5 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/serverless_spec.py b/pinecone/core/client/model/serverless_spec.py index 1fd00c6d0..7f967c6e0 100644 --- a/pinecone/core/client/model/serverless_spec.py +++ b/pinecone/core/client/model/serverless_spec.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -156,7 +156,7 @@ def _from_openapi_data(cls, cloud, region, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -241,7 +241,7 @@ def __init__(self, cloud, region, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -268,5 +268,5 @@ def __init__(self, cloud, region, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/single_query_results.py b/pinecone/core/client/model/single_query_results.py index 9fe8c4313..389af078c 100644 --- a/pinecone/core/client/model/single_query_results.py +++ b/pinecone/core/client/model/single_query_results.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -155,7 +155,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -236,7 +236,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -261,5 +261,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/sparse_values.py b/pinecone/core/client/model/sparse_values.py index 62374846e..95bc4e945 100644 --- a/pinecone/core/client/model/sparse_values.py +++ b/pinecone/core/client/model/sparse_values.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -155,7 +155,7 @@ def _from_openapi_data(cls, indices, values, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -240,7 +240,7 @@ def __init__(self, indices, values, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -267,5 +267,5 @@ def __init__(self, indices, values, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/update_request.py b/pinecone/core/client/model/update_request.py index 3fb151e8c..aebfd0c4b 100644 --- a/pinecone/core/client/model/update_request.py +++ b/pinecone/core/client/model/update_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -172,7 +172,7 @@ def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -259,7 +259,7 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -285,5 +285,5 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/upsert_request.py b/pinecone/core/client/model/upsert_request.py index 5e20e01ee..20d79830b 100644 --- a/pinecone/core/client/model/upsert_request.py +++ b/pinecone/core/client/model/upsert_request.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -159,7 +159,7 @@ def _from_openapi_data(cls, vectors, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -243,7 +243,7 @@ def __init__(self, vectors, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -269,5 +269,5 @@ def __init__(self, vectors, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/upsert_response.py b/pinecone/core/client/model/upsert_response.py index 3a0c766cc..22b30a822 100644 --- a/pinecone/core/client/model/upsert_response.py +++ b/pinecone/core/client/model/upsert_response.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError @@ -146,7 +146,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -226,7 +226,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -251,5 +251,5 @@ def __init__(self, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model/vector.py b/pinecone/core/client/model/vector.py index 7c94ea867..031506e5b 100644 --- a/pinecone/core/client/model/vector.py +++ b/pinecone/core/client/model/vector.py @@ -12,7 +12,7 @@ import sys # noqa: F401 from pinecone.core.client.model_utils import ( # noqa: F401 - ApiTypeError, + PineconeApiTypeError, ModelComposed, ModelNormal, ModelSimple, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import ApiAttributeError +from pinecone.core.client.exceptions import PineconeApiAttributeError def lazy_import(): @@ -169,7 +169,7 @@ def _from_openapi_data(cls, id, values, *args, **kwargs): # noqa: E501 self = super(OpenApiModel, cls).__new__(cls) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -256,7 +256,7 @@ def __init__(self, id, values, *args, **kwargs): # noqa: E501 _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: - raise ApiTypeError( + raise PineconeApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, @@ -283,5 +283,5 @@ def __init__(self, id, values, *args, **kwargs): # noqa: E501 continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + 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/client/model_utils.py b/pinecone/core/client/model_utils.py index f07308a93..530b7c819 100644 --- a/pinecone/core/client/model_utils.py +++ b/pinecone/core/client/model_utils.py @@ -19,10 +19,10 @@ from dateutil.parser import parse from pinecone.core.client.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, + PineconeApiKeyError, + PineconeApiAttributeError, + PineconeApiTypeError, + PineconeApiValueError, ) none_type = type(None) @@ -129,7 +129,7 @@ def set_attribute(self, name, value): if name in self.openapi_types: required_types_mixed = self.openapi_types[name] elif self.additional_properties_type is None: - raise ApiAttributeError( + raise PineconeApiAttributeError( "{0} has no attribute '{1}'".format( type(self).__name__, name), path_to_item @@ -144,7 +144,7 @@ def set_attribute(self, name, value): valid_classes=(str,), key_type=True ) - raise ApiTypeError( + raise PineconeApiTypeError( error_msg, path_to_item=path_to_item, valid_classes=(str,), @@ -238,7 +238,7 @@ def __new__(cls, *args, **kwargs): else: # The input data does not contain the discriminator property. path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( + raise PineconeApiValueError( "Cannot deserialize input data due to missing discriminator. " "The discriminator property '%s' is missing at path: %s" % (discr_propertyname_js, path_to_item) @@ -254,7 +254,7 @@ def __new__(cls, *args, **kwargs): path_to_item = kwargs.get('_path_to_item', ()) disc_prop_value = kwargs.get( discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( + raise PineconeApiValueError( "Cannot deserialize input data due to invalid discriminator " "value. The OpenAPI document has no mapping for discriminator " "property '%s'='%s' at path: %s" % @@ -354,7 +354,7 @@ def _new_from_openapi_data(cls, *args, **kwargs): else: # The input data does not contain the discriminator property. path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( + raise PineconeApiValueError( "Cannot deserialize input data due to missing discriminator. " "The discriminator property '%s' is missing at path: %s" % (discr_propertyname_js, path_to_item) @@ -370,7 +370,7 @@ def _new_from_openapi_data(cls, *args, **kwargs): path_to_item = kwargs.get('_path_to_item', ()) disc_prop_value = kwargs.get( discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( + raise PineconeApiValueError( "Cannot deserialize input data due to invalid discriminator " "value. The OpenAPI document has no mapping for discriminator " "property '%s'='%s' at path: %s" % @@ -439,7 +439,7 @@ def __getitem__(self, name): if name in self: return self.get(name) - raise ApiAttributeError( + raise PineconeApiAttributeError( "{0} has no attribute '{1}'".format( type(self).__name__, name), [e for e in [self._path_to_item, name] if e] @@ -494,7 +494,7 @@ def __getitem__(self, name): if name in self: return self.get(name) - raise ApiAttributeError( + raise PineconeApiAttributeError( "{0} has no attribute '{1}'".format( type(self).__name__, name), [e for e in [self._path_to_item, name] if e] @@ -589,7 +589,7 @@ def __setitem__(self, name, value): - have additionalProperties set """ if name not in self.openapi_types: - raise ApiAttributeError( + raise PineconeApiAttributeError( "{0} has no attribute '{1}'".format( type(self).__name__, name), [e for e in [self._path_to_item, name] if e] @@ -629,7 +629,7 @@ def get(self, name, default=None): elif len_values == 1: return values[0] elif len_values > 1: - raise ApiValueError( + raise PineconeApiValueError( "Values stored for property {0} in {1} differ when looking " "at self and self's composed instances. All values must be " "the same".format(name, type(self).__name__), @@ -640,7 +640,7 @@ def __getitem__(self, name): """get the value of an attribute using square-bracket notation: `instance[attr]`""" value = self.get(name, self.__unset_attribute_value__) if value is self.__unset_attribute_value__: - raise ApiAttributeError( + raise PineconeApiAttributeError( "{0} has no attribute '{1}'".format( type(self).__name__, name), [e for e in [self._path_to_item, name] if e] @@ -820,7 +820,7 @@ def check_allowed_values(allowed_values, input_variable_path, input_values): set(these_allowed_values))): invalid_values = ", ".join( map(str, set(input_values) - set(these_allowed_values))), - raise ApiValueError( + raise PineconeApiValueError( "Invalid values for `%s` [%s], must be a subset of [%s]" % ( input_variable_path[0], @@ -833,7 +833,7 @@ def check_allowed_values(allowed_values, input_variable_path, input_values): input_values.keys()).issubset(set(these_allowed_values))): invalid_values = ", ".join( map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( + raise PineconeApiValueError( "Invalid keys in `%s` [%s], must be a subset of [%s]" % ( input_variable_path[0], @@ -843,7 +843,7 @@ def check_allowed_values(allowed_values, input_variable_path, input_values): ) elif (not isinstance(input_values, (list, dict)) and input_values not in these_allowed_values): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s` (%s), must be one of %s" % ( input_variable_path[0], @@ -890,7 +890,7 @@ def check_validations( isinstance(input_values, (int, float)) and not (float(input_values) / current_validations['multiple_of']).is_integer()): # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, value must be a multiple of " "`%s`" % ( input_variable_path[0], @@ -901,7 +901,7 @@ def check_validations( if (is_json_validation_enabled('maxLength', configuration) and 'max_length' in current_validations and len(input_values) > current_validations['max_length']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, length must be less than or equal to " "`%s`" % ( input_variable_path[0], @@ -912,7 +912,7 @@ def check_validations( if (is_json_validation_enabled('minLength', configuration) and 'min_length' in current_validations and len(input_values) < current_validations['min_length']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, length must be greater than or equal to " "`%s`" % ( input_variable_path[0], @@ -923,7 +923,7 @@ def check_validations( if (is_json_validation_enabled('maxItems', configuration) and 'max_items' in current_validations and len(input_values) > current_validations['max_items']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, number of items must be less than or " "equal to `%s`" % ( input_variable_path[0], @@ -958,7 +958,7 @@ def check_validations( if (is_json_validation_enabled('exclusiveMaximum', configuration) and 'exclusive_maximum' in current_validations and max_val >= current_validations['exclusive_maximum']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, must be a value less than `%s`" % ( input_variable_path[0], current_validations['exclusive_maximum'] @@ -968,7 +968,7 @@ def check_validations( if (is_json_validation_enabled('maximum', configuration) and 'inclusive_maximum' in current_validations and max_val > current_validations['inclusive_maximum']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, must be a value less than or equal to " "`%s`" % ( input_variable_path[0], @@ -979,7 +979,7 @@ def check_validations( if (is_json_validation_enabled('exclusiveMinimum', configuration) and 'exclusive_minimum' in current_validations and min_val <= current_validations['exclusive_minimum']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, must be a value greater than `%s`" % ( input_variable_path[0], @@ -990,7 +990,7 @@ def check_validations( if (is_json_validation_enabled('minimum', configuration) and 'inclusive_minimum' in current_validations and min_val < current_validations['inclusive_minimum']): - raise ApiValueError( + raise PineconeApiValueError( "Invalid value for `%s`, must be a value greater than or equal " "to `%s`" % ( input_variable_path[0], @@ -1010,7 +1010,7 @@ def check_validations( # Don't print the regex flags if the flags are not # specified in the OAS document. err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) + raise PineconeApiValueError(err_msg) def order_response_types(required_types): @@ -1041,7 +1041,7 @@ def index_getter(class_or_instance): return COERCION_INDEX_BY_TYPE[ModelSimple] elif class_or_instance in COERCION_INDEX_BY_TYPE: return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) + raise PineconeApiValueError("Unsupported type: %s" % class_or_instance) sorted_types = sorted( required_types, @@ -1196,7 +1196,7 @@ def get_type_error(var_value, path_to_item, valid_classes, key_type=False): valid_classes=valid_classes, key_type=key_type ) - return ApiTypeError( + return PineconeApiTypeError( error_msg, path_to_item=path_to_item, valid_classes=valid_classes, @@ -1248,7 +1248,7 @@ def deserialize_primitive(data, klass, path_to_item): return converted_value except (OverflowError, ValueError) as ex: # parse can raise OverflowError - raise ApiValueError( + raise PineconeApiValueError( "{0}Failed to parse {1} as {2}".format( additional_message, repr(data), klass.__name__ ), @@ -1328,9 +1328,9 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, model instance Raise: - ApiTypeError - ApiValueError - ApiKeyError + PineconeApiTypeError + PineconeApiValueError + PineconeApiKeyError """ kw_args = dict(_check_type=check_type, @@ -1408,9 +1408,9 @@ def attempt_convert_item(input_value, valid_classes, path_to_item, instance (any) the fixed item Raises: - ApiTypeError - ApiValueError - ApiKeyError + PineconeApiTypeError + PineconeApiValueError + PineconeApiKeyError """ valid_classes_ordered = order_response_types(valid_classes) valid_classes_coercible = remove_uncoercible( @@ -1431,7 +1431,7 @@ def attempt_convert_item(input_value, valid_classes, path_to_item, return deserialize_file(input_value, configuration) return deserialize_primitive(input_value, valid_class, path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + except (PineconeApiTypeError, PineconeApiValueError, PineconeApiKeyError) as conversion_exc: if must_convert: raise conversion_exc # if we have conversion errors when must_convert == False @@ -1527,7 +1527,7 @@ def validate_and_convert_types(input_value, required_types_mixed, path_to_item, the correctly typed value Raises: - ApiTypeError + PineconeApiTypeError """ results = get_required_type_classes(required_types_mixed, spec_property_naming) valid_classes, child_req_types_by_current_type = results @@ -1750,7 +1750,7 @@ def get_allof_instances(self, model_args, constant_args): allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: - raise ApiValueError( + raise PineconeApiValueError( "Invalid inputs given to generate an instance of '%s'. The " "input data was invalid for the allOf schema '%s' in the composed " "schema '%s'. Error=%s" % ( @@ -1826,13 +1826,13 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): except Exception: pass if len(oneof_instances) == 0: - raise ApiValueError( + raise PineconeApiValueError( "Invalid inputs given to generate an instance of %s. None " "of the oneOf schemas matched the input data." % cls.__name__ ) elif len(oneof_instances) > 1: - raise ApiValueError( + raise PineconeApiValueError( "Invalid inputs given to generate an instance of %s. Multiple " "oneOf schemas matched the inputs, but a max of one is allowed." % cls.__name__ @@ -1872,7 +1872,7 @@ def get_anyof_instances(self, model_args, constant_args): except Exception: pass if len(anyof_instances) == 0: - raise ApiValueError( + raise PineconeApiValueError( "Invalid inputs given to generate an instance of %s. None of the " "anyOf schemas matched the inputs." % self.__class__.__name__ diff --git a/pinecone/core/client/rest.py b/pinecone/core/client/rest.py index 9a51bb9b4..a7b8d432e 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/client/rest.py @@ -18,7 +18,7 @@ import urllib3 -from pinecone.core.client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError +from pinecone.core.client.exceptions import PineconeApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, PineconeApiValueError class bcolors: @@ -147,7 +147,7 @@ def request(self, method, url, query_params=None, headers=None, print(bcolors.OKBLUE + "curl -X {method} '{url}' {formatted_headers} -d '{data}'".format(method=method, url=formatted_url, formatted_headers=formatted_headers, data=formatted_body) + bcolors.ENDC) if post_params and body: - raise ApiValueError( + raise PineconeApiValueError( "body parameter cannot be used with post_params parameter." ) @@ -217,7 +217,7 @@ def request(self, method, url, query_params=None, headers=None, msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" - raise ApiException(status=0, reason=msg) + raise PineconeApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, @@ -227,7 +227,7 @@ def request(self, method, url, query_params=None, headers=None, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) + raise PineconeApiException(status=0, reason=msg) if os.environ.get('PINECONE_DEBUG_CURL'): o = RESTResponse(r) @@ -257,7 +257,7 @@ def request(self, method, url, query_params=None, headers=None, if 500 <= r.status <= 599: raise ServiceException(http_resp=r) - raise ApiException(http_resp=r) + raise PineconeApiException(http_resp=r) return r diff --git a/pinecone/exceptions.py b/pinecone/exceptions.py index 98610be39..24319f657 100644 --- a/pinecone/exceptions.py +++ b/pinecone/exceptions.py @@ -1,19 +1,16 @@ from .core.client.exceptions import ( - OpenApiException, - ApiAttributeError, - ApiTypeError, - ApiValueError, - ApiKeyError, - ApiException, + PineconeException, + PineconeApiAttributeError, + PineconeApiTypeError, + PineconeApiValueError, + PineconeApiKeyError, + PineconeApiException, NotFoundException, UnauthorizedException, ForbiddenException, ServiceException, ) -class PineconeException(Exception): - """The base exception class for all Pinecone client exceptions.""" - class PineconeProtocolError(PineconeException): """Raised when something unexpected happens mid-request/response.""" @@ -22,14 +19,13 @@ class PineconeConfigurationError(PineconeException): __all__ = [ "PineconeConfigurationError", - "PineconeException", "PineconeProtocolError", - "OpenApiException", - "ApiAttributeError", - "ApiTypeError", - "ApiValueError", - "ApiKeyError", - "ApiException", + "PineconeException", + "PineconeApiAttributeError", + "PineconeApiTypeError", + "PineconeApiValueError", + "PineconeApiKeyError", + "PineconeApiException", "NotFoundException", "UnauthorizedException", "ForbiddenException", diff --git a/tests/integ/test_index.py b/tests/integ/test_index.py index cb52b6c56..2df35b986 100644 --- a/tests/integ/test_index.py +++ b/tests/integ/test_index.py @@ -5,7 +5,7 @@ import responses as req_responses import pinecone -from pinecone import ApiTypeError, ApiException +from pinecone import PineconeApiTypeError, PineconeApiException responses_req = Responses() responses = Responses("requests.packages.urllib3") @@ -38,7 +38,7 @@ def test_invalid_upsert_request_vector_value_type(): ) pinecone.init("example-api-key", environment="example-environment") - with pytest.raises(ApiException) as exc_info: + with pytest.raises(PineconeApiException) as exc_info: index = pinecone.Index("example-index") resp = index.upsert(vectors=[("vec1", [0.1] * 8), ("vec2", [0.2] * 8)]) @@ -133,6 +133,6 @@ def _test_invalid_delete_response_wrong_type(): index = pinecone.Index("example-index") - with pytest.raises(ApiTypeError) as exc_info: + with pytest.raises(PineconeApiTypeError) as exc_info: resp = index.delete(ids=["vec1", "vec2"]) assert resp.deleted_count == 2 diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 79b78419b..d8d333e20 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,7 +1,7 @@ import pytest import random import time -from pinecone import Pinecone, NotFoundException, ApiException +from pinecone import Pinecone, NotFoundException, PineconeApiException from .helpers.helpers import generate_index_name, get_environment_var @pytest.fixture() @@ -66,7 +66,7 @@ def delete_with_retry(client, index_name, retries=0, sleep_interval=5): client.delete_index(index_name, -1) except NotFoundException: pass - except ApiException as e: + except PineconeApiException as e: if e.error.code == 'PRECONDITON_FAILED': if retries > 5: raise 'Unable to delete index ' + index_name diff --git a/tests/integration/test_create_index_api_errors.py b/tests/integration/test_create_index_api_errors.py index 8eeb3f3db..89ae97946 100644 --- a/tests/integration/test_create_index_api_errors.py +++ b/tests/integration/test_create_index_api_errors.py @@ -1,25 +1,25 @@ import pytest -from pinecone import ApiException, ApiValueError +from pinecone import PineconeApiException, PineconeApiValueError class TestCreateIndexApiErrorCases: def test_create_index_with_invalid_name(self, client, create_sl_index_params): create_sl_index_params['name'] = '-invalid-name' - with pytest.raises(ApiException): + with pytest.raises(PineconeApiException): client.create_index(**create_sl_index_params) def test_create_index_invalid_metric(self, client, create_sl_index_params): create_sl_index_params['metric'] = 'invalid' - with pytest.raises(ApiValueError): + with pytest.raises(PineconeApiValueError): client.create_index(**create_sl_index_params) def test_create_index_with_invalid_neg_dimension(self, client, create_sl_index_params): create_sl_index_params['dimension'] = -1 - with pytest.raises(ApiValueError): + with pytest.raises(PineconeApiValueError): client.create_index(**create_sl_index_params) def test_create_index_that_already_exists(self, client, create_sl_index_params): client.create_index(**create_sl_index_params) - with pytest.raises(ApiException): + with pytest.raises(PineconeApiException): client.create_index(**create_sl_index_params) @pytest.mark.skip(reason='Bug filed https://app.asana.com/0/1205078872348810/1205917627868143') @@ -27,5 +27,5 @@ def test_create_index_w_incompatible_options(self, client, create_sl_index_param create_sl_index_params['pod_type'] = 'p1.x2' create_sl_index_params['environment'] = 'us-east1-gcp' create_sl_index_params['replicas'] = 2 - with pytest.raises(ApiException): + with pytest.raises(PineconeApiException): client.create_index(**create_sl_index_params) \ No newline at end of file diff --git a/tests/integration/test_create_index_type_errors.py b/tests/integration/test_create_index_type_errors.py index b4f649c07..252b6840b 100644 --- a/tests/integration/test_create_index_type_errors.py +++ b/tests/integration/test_create_index_type_errors.py @@ -1,10 +1,10 @@ import pytest -from pinecone import ApiTypeError +from pinecone import 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(ApiTypeError): + with pytest.raises(PineconeApiTypeError): client.create_index(**create_sl_index_params) def test_create_index_with_missing_dimension(self, client, create_sl_index_params): diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index aebd002c6..cc08dd2b9 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,5 +1,5 @@ import pinecone -from pinecone.exceptions import ApiKeyError, PineconeConfigurationError +from pinecone.exceptions import PineconeApiKeyError, PineconeConfigurationError from pinecone.config import PineconeConfig from pinecone.core.client.configuration import Configuration as OpenApiConfiguration From 5226fcf94ccd6ddf632a004614b6445e98159492 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 1 Dec 2023 15:24:22 -0500 Subject: [PATCH 24/39] [spruce] Fix issue with polling after delete index (#253) ## Problem There was a small error in a recent change to add a `names()` utility method on the response from `Pinecone#list_indexes` to facilitate easy iteration over index names. This resulted in an error when deleting indexes: ``` def get_remaining(): > return name in api_instance.list_indexes().names() E TypeError: 'NoneType' object is not callable ``` This error got introduced because `api_instance.list_indexes()` and `self.list_indexes()` are both a thing in this context, but only `self.list_indexes()` returns a result with the `.names()` helper. ## Solution Call names on the correct object to avoid the error. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) ## Test Plan I confirmed with manual testing that this resolves the issue. --- pinecone/control/pinecone.py | 2 +- tests/unit/models/test_index_list.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 93ec66ab2..56ee1c513 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -123,7 +123,7 @@ def delete_index(self, name: str, timeout: Optional[int] = None): self.index_host_store.delete_host(self.config, name) def get_remaining(): - return name in api_instance.list_indexes().names() + return name in self.list_indexes().names() if timeout == -1: return diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py index d28f472ca..8033131f4 100644 --- a/tests/unit/models/test_index_list.py +++ b/tests/unit/models/test_index_list.py @@ -57,4 +57,10 @@ def test_index_list_proxies_methods(self, index_list_response): # Forward compatibility, in case we add more attributes to IndexList for pagination assert IndexList(index_list_response).index_list.indexes == index_list_response.indexes + def test_when_results_are_empty(self): + iil = IndexList(OpenApiIndexList(indexes=[])) + assert len(iil) == 0 + assert iil.index_list.indexes == [] + assert iil.indexes == [] + assert iil.names() == [] From 379213923533c68550ad0abd4d14680157734e73 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Wed, 20 Dec 2023 17:16:12 -0500 Subject: [PATCH 25/39] [Bug] Stop coercion of strings into datetime objects (#255) ## Problem Sometimes when strings are stored as metadata values, later fetching or querying causes those values to be coerced into datetime objects by the client before they are presented to the caller. This is a default behavior in the generated openapi client that is a result of the python `datetime` constructor working quite hard to turn things into dates. We've seen scenarios where this was not desired, so for now we will disable this conversion process to have consistent handling of all strings. People who desire date objects can easily implement the conversion themselves. ## Solution - Update openapi templates to comment out and remove logic related to converting strings into date and datetime objects. - Regenerate client with new templates - Add unit test verifying the type coercion does not take place. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) ## Test Plan `poetry run pytest tests/unit/data` --- pinecone/core/client/model_utils.py | 96 ++++++++++++------------ tests/unit/data/test_datetime_parsing.py | 13 ++++ 2 files changed, 60 insertions(+), 49 deletions(-) create mode 100644 tests/unit/data/test_datetime_parsing.py diff --git a/pinecone/core/client/model_utils.py b/pinecone/core/client/model_utils.py index 530b7c819..308174e8e 100644 --- a/pinecone/core/client/model_utils.py +++ b/pinecone/core/client/model_utils.py @@ -16,8 +16,6 @@ import re import tempfile -from dateutil.parser import parse - from pinecone.core.client.exceptions import ( PineconeApiKeyError, PineconeApiAttributeError, @@ -63,7 +61,7 @@ def __get__(self, instance, cls=None): return result -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) +PRIMITIVE_TYPES = (list, float, int, bool, str, file_type) def allows_single_value_input(cls): """ @@ -699,8 +697,8 @@ def __eq__(self, other): float: 6, int: 7, bool: 8, - datetime: 9, - date: 10, + # datetime: 9, + # date: 10, str: 11, file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. } @@ -709,8 +707,8 @@ def __eq__(self, other): # when we have a valid type already and we want to try converting # to another type UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), + # (str, datetime), + # (str, date), (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float. (list, ModelComposed), (dict, ModelComposed), @@ -754,8 +752,8 @@ def __eq__(self, other): (list, ModelSimple), # (str, int), # (str, float), - (str, datetime), - (str, date), + # (str, datetime), + # (str, date), # (int, str), # (float, str), (str, file_type) @@ -794,12 +792,12 @@ def get_simple_class(input_value): return bool elif isinstance(input_value, int): return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date + # elif isinstance(input_value, datetime): + # # this must be higher than the date check because + # # isinstance(datetime_instance, date) == True + # return datetime + # elif isinstance(input_value, date): + # return date elif isinstance(input_value, str): return str return type(input_value) @@ -1210,42 +1208,42 @@ def deserialize_primitive(data, klass, path_to_item): :param data: str/int/float :param klass: str/class the class to convert to - :return: int, float, str, bool, date, datetime + :return: int, float, str, bool """ additional_message = "" try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 and - parsed_datetime.minute == 0 and - parsed_datetime.second == 0 and - parsed_datetime.tzinfo is None and - 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError('This is not a float') - return converted_value + # if klass in {datetime, date}: + # additional_message = ( + # "If you need your parameter to have a fallback " + # "string value, please set its type as `type: {}` in your " + # "spec. That allows the value to be any type. " + # ) + # if klass == datetime: + # if len(data) < 8: + # raise ValueError("This is not a datetime") + # # The string should be in iso8601 datetime format. + # parsed_datetime = parse(data) + # date_only = ( + # parsed_datetime.hour == 0 and + # parsed_datetime.minute == 0 and + # parsed_datetime.second == 0 and + # parsed_datetime.tzinfo is None and + # 8 <= len(data) <= 10 + # ) + # if date_only: + # raise ValueError("This is a date, not a datetime") + # return parsed_datetime + # elif klass == date: + # if len(data) < 8: + # raise ValueError("This is not a date") + # return parse(data).date() + # else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value except (OverflowError, ValueError) as ex: # parse can raise OverflowError raise PineconeApiValueError( @@ -1782,7 +1780,7 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): and path to item. Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + model_arg: (int, float, bool, str, ModelSimple, None): the value to assign to a primitive class or ModelSimple class Notes: - this is only passed in when oneOf includes types which are not object diff --git a/tests/unit/data/test_datetime_parsing.py b/tests/unit/data/test_datetime_parsing.py new file mode 100644 index 000000000..cbce1bd06 --- /dev/null +++ b/tests/unit/data/test_datetime_parsing.py @@ -0,0 +1,13 @@ +from pinecone import Vector, Config +from datetime import datetime + +class TestDatetimeConversion: + def test_datetimes_not_coerced(self): + vec = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'created_at': '7th of January, 2023'}, _check_type=True, _configuration=Config()) + assert vec.metadata['created_at'] == '7th of January, 2023' + assert vec.metadata['created_at'].__class__ == str + + def test_dates_not_coerced(self): + vec = Vector(id='1', values=[0.1, 0.2, 0.3], metadata={'created_at': '8/12/2024'}, _check_type=True, _configuration=Config()) + assert vec.metadata['created_at'] == '8/12/2024' + assert vec.metadata['created_at'].__class__ == str From bcf5393af8e948b54ad3148976aedf80ad1b2af8 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 26 Dec 2023 10:38:39 -0600 Subject: [PATCH 26/39] Parameterize integration tests on environment (#256) ## Problem I want to be able to run the integration tests with a variety of environments. ## Solution Add some variables to the test matrix and wire them into the test execution. We can expand this list over time to grow our test surface area. ## Type of Change - [x] Infrastructure change (CI configs, etc) --- .github/workflows/testing.yaml | 18 +++++++++++++++--- tests/integration/conftest.py | 18 +++++++++++++++--- tests/integration/helpers/helpers.py | 5 +++-- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index fd822de5f..1306bf3bf 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -37,19 +37,25 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.8, 3.11] pineconeEnv: - prod # - staging + testConfig: + - python-version: 3.8 # Do one test run with 3.8 for sanity check + pod: { environment: 'us-east1-gcp'} + serverless: { cloud: 'aws', region: 'us-west-2'} + - python-version: 3.11 + pod: { environment: 'us-east1-gcp'} + serverless: { cloud: 'aws', region: 'us-west-2'} max-parallel: 1 fail-fast: false steps: - uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.testConfig.python-version }} uses: actions/setup-python@v4 with: - python-version: ${{ matrix.python-version }} + python-version: ${{ matrix.testConfig.python-version }} - name: Setup Poetry uses: ./.github/actions/setup-poetry @@ -61,6 +67,9 @@ jobs: PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.python-version}}" + POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} + SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} + SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} - name: Run integration tests (REST, staging) if: matrix.pineconeEnv == 'staging' @@ -69,6 +78,9 @@ jobs: PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY_STAGING }} GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.python-version}}" + POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} + SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} + SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} units-grpc: name: Unit tests (GRPC) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index d8d333e20..4e8f3b9ab 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -9,15 +9,27 @@ def client(): api_key = get_environment_var('PINECONE_API_KEY') return Pinecone(api_key=api_key) +@pytest.fixture() +def pod_environment(): + return get_environment_var('POD_ENVIRONMENT', 'us-east1-gcp') + +@pytest.fixture() +def serverless_cloud(): + return get_environment_var('SERVERLESS_CLOUD', 'aws') + +@pytest.fixture() +def serverless_region(): + return get_environment_var('SERVERLESS_REGION', 'us-west-2') + @pytest.fixture() def environment(): return get_environment_var('PINECONE_ENVIRONMENT') @pytest.fixture() -def create_sl_index_params(index_name): +def create_sl_index_params(index_name, serverless_cloud, serverless_region): spec = {"serverless": { - 'cloud': 'aws', - 'region': 'us-west-2' + 'cloud': serverless_cloud, + 'region': serverless_region }} return dict(name=index_name, dimension=10, metric='cosine', spec=spec) diff --git a/tests/integration/helpers/helpers.py b/tests/integration/helpers/helpers.py index 1e40f6fac..1d19e8239 100644 --- a/tests/integration/helpers/helpers.py +++ b/tests/integration/helpers/helpers.py @@ -2,6 +2,7 @@ import os import random import string +from typing import Any def random_string(length): return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) @@ -37,8 +38,8 @@ def generate_index_name(test_name: str) -> str: return index_name.lower() -def get_environment_var(name: str) -> str: - val = os.getenv(name) +def get_environment_var(name: str, defaultVal: Any = None) -> str: + val = os.getenv(name, defaultVal) if (val is None): raise Exception('Expected environment variable ' + name + ' is not set') else: From 2a2636972aeefad2a532eddc62fea6bedbf93bcd Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Wed, 27 Dec 2023 08:22:30 -0600 Subject: [PATCH 27/39] Wire up pool_threads config (#258) ## Problem We need to expose the `pool_threads` config in the new `Pinecone` constructor. This config property is ultimately used by the `ApiClient` class ([see here](https://github.com/pinecone-io/pinecone-python-client/blob/e81807de685d08297ea4ad642639fbc0d0ab24fd/pinecone/core/client/api_client.py#L61)), which is generated by the OpenAPI python generator. It is only used when performing operations over REST using the `async_req=True` param. ## Solution Add a property and wire it up with the underlying `ApiClient` object and `Index` constructor. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) --------- Co-authored-by: Austin DeNoble --- pinecone/control/pinecone.py | 11 +++++++---- pinecone/grpc/pinecone.py | 8 +++++--- tests/unit/test_config.py | 13 ++++++++++--- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 56ee1c513..000709607 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -24,6 +24,7 @@ def __init__( host: Optional[str] = None, config: Optional[Config] = None, additional_headers: Optional[Dict[str, str]] = {}, + pool_threads: Optional[int] = 1, index_api: Optional[IndexOperationsApi] = None, **kwargs, ): @@ -39,7 +40,8 @@ def __init__( if index_api: self.index_api = index_api else: - api_client = ApiClient(configuration=self.config.openapi_config) + self.pool_threads = pool_threads + api_client = ApiClient(configuration=self.config.openapi_config, pool_threads=self.pool_threads) api_client.user_agent = get_user_agent() extra_headers = self.config.additional_headers or {} for key, value in extra_headers.items(): @@ -222,6 +224,7 @@ def _get_status(self, name: str): response = api_instance.describe_index(name) return response["status"] - def Index(self, name: str): - index_host = self.index_host_store.get_host(self.index_api, self.config, name) - return Index(api_key=self.config.api_key, host=index_host) + def Index(self, name: str, host: Optional[str] = None): + if host is None: + host = self.index_host_store.get_host(self.index_api, self.config, name) + return Index(api_key=self.config.api_key, host=host, pool_threads=self.pool_threads) diff --git a/pinecone/grpc/pinecone.py b/pinecone/grpc/pinecone.py index 87ecf871d..378c07631 100644 --- a/pinecone/grpc/pinecone.py +++ b/pinecone/grpc/pinecone.py @@ -1,9 +1,11 @@ from ..control.pinecone import Pinecone from ..config.config import ConfigBuilder from .index_grpc import GRPCIndex +from typing import Optional class PineconeGRPC(Pinecone): - def Index(self, name: str): - index_host = self.index_host_store.get_host(self.index_api, self.config, name) - config = ConfigBuilder.build(api_key=self.config.api_key, host=index_host) + def Index(self, name: str, host: Optional[str] = None): + if host is None: + host = self.index_host_store.get_host(self.index_api, self.config, name) + config = ConfigBuilder.build(api_key=self.config.api_key, host=host) return GRPCIndex(index_name=name, config=config) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index cc08dd2b9..058e6091d 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,5 +1,5 @@ -import pinecone -from pinecone.exceptions import PineconeApiKeyError, PineconeConfigurationError +from pinecone import Pinecone +from pinecone.exceptions import PineconeConfigurationError from pinecone.config import PineconeConfig from pinecone.core.client.configuration import Configuration as OpenApiConfiguration @@ -73,4 +73,11 @@ def test_resolution_order_kwargs_over_env_vars(self): def test_errors_when_no_api_key_is_present(self): with pytest.raises(PineconeConfigurationError): - PineconeConfig.build() \ No newline at end of file + PineconeConfig.build() + + def test_config_pool_threads(self): + pc = Pinecone(api_key="test-api-key", host="test-controller-host", pool_threads=10) + assert pc.index_api.api_client.pool_threads == 10 + idx = pc.Index(host='my-index-host', name='my-index-name') + assert idx._api_client.pool_threads == 10 + From e53ea92e1d0cd3d0f4924474049f3d7bc567457e Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Thu, 28 Dec 2023 12:02:52 -0600 Subject: [PATCH 28/39] Update publish job with pypi api tokens (#262) ## Problem Now that PyPI has required 2FA for all accounts, we have to publish using API Tokens instead of username and password. ## Solution - Update workflows with pypi api token. - Delete unused jobs that publish to testpypi ## Type of Change - [x] Infrastructure change (CI configs, etc) ## Test Plan Describe specific steps for validating this change. --- .github/workflows/alpha-release.yaml | 4 +- .github/workflows/nightly-release.yaml | 4 +- .../workflows/nightly-spruce-dev-release.yaml | 65 ------------------- .github/workflows/release-spruce.yaml | 52 --------------- .github/workflows/release.yaml | 8 +-- 5 files changed, 6 insertions(+), 127 deletions(-) delete mode 100644 .github/workflows/nightly-spruce-dev-release.yaml delete mode 100644 .github/workflows/release-spruce.yaml diff --git a/.github/workflows/alpha-release.yaml b/.github/workflows/alpha-release.yaml index 9c0c458c6..aeac3e294 100644 --- a/.github/workflows/alpha-release.yaml +++ b/.github/workflows/alpha-release.yaml @@ -38,5 +38,5 @@ jobs: prereleaseSuffix: ${{ inputs.prereleaseSuffix }} TWINE_REPOSITORY: 'pypi' secrets: - PYPI_USERNAME: ${{ secrets.PROD_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PASSWORD }} + PYPI_USERNAME: __token__ + PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PUBLISH_TOKEN }} diff --git a/.github/workflows/nightly-release.yaml b/.github/workflows/nightly-release.yaml index 1a18dbd78..19b7daf75 100644 --- a/.github/workflows/nightly-release.yaml +++ b/.github/workflows/nightly-release.yaml @@ -60,6 +60,6 @@ jobs: id: pypi_upload env: TWINE_REPOSITORY: pypi - PYPI_USERNAME: ${{ secrets.PROD_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PASSWORD }} + PYPI_USERNAME: __token__ + PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PUBLISH_TOKEN }} run: make upload diff --git a/.github/workflows/nightly-spruce-dev-release.yaml b/.github/workflows/nightly-spruce-dev-release.yaml deleted file mode 100644 index be49ecf8d..000000000 --- a/.github/workflows/nightly-spruce-dev-release.yaml +++ /dev/null @@ -1,65 +0,0 @@ -name: 'Test PyPI Spruce Release: Nightly (pinecone-client-spruce-dev)' - -on: - workflow_dispatch: - schedule: - - cron: '0 0 * * *' - -jobs: - run-tests: - uses: './.github/workflows/testing.yaml' - secrets: inherit - - pypi-spruce-nightly: - needs: run-tests - timeout-minutes: 30 - name: pypi-nightly - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - ref: spruce - - - name: Get recent changes - id: list-commits - run: | - recentCommits=$(git log --since=yesterday --oneline) - echo "commits=$recentCommits" >> "$GITHUB_OUTPUT" - - - name: Abort if no recent changes - if: steps.list-commits.outputs.commits == '' - uses: andymckay/cancel-action@0.3 - - - name: Set spruce dev version - run: | - versionFile="pinecone/__version__" - currentDate=$(date +%Y%m%d%H%M%S) - versionNumber=$(cat $versionFile) - devVersion="${versionNumber}.dev${currentDate}.spruceDev" - echo "$devVersion" > $versionFile - - - name: Adjust module name - run: | - sed -i 's/pinecone-client/pinecone-client-spruce-dev/g' pyproject.toml - - - name: Update README - run: | - echo "This is a nightly Spruce developer build of the Pinecone Python client. It is not intended for production use." > README.md - - - uses: actions/setup-python@v4 - with: - python-version: 3.x - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - - - name: Build Python client - run: make package - - - name: Upload Python Spruce client to Test PyPI - env: - TWINE_REPOSITORY: testpypi - PYPI_USERNAME: ${{ secrets.TEST_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} - run: make upload-spruce diff --git a/.github/workflows/release-spruce.yaml b/.github/workflows/release-spruce.yaml deleted file mode 100644 index 178299ac1..000000000 --- a/.github/workflows/release-spruce.yaml +++ /dev/null @@ -1,52 +0,0 @@ -name: 'Test PyPI Release: Spruce build (pinecone-client-spruce)' - -on: - workflow_dispatch: {} - -jobs: - testing: - uses: './.github/workflows/testing.yaml' - secrets: inherit - - version-and-release-spruce: - timeout-minutes: 30 - name: Release Spruce dev build to test pypi - runs-on: ubuntu-latest - steps: - - name: Checkout Spruce - uses: actions/checkout@v4 - with: - ref: spruce - - - name: Set spruce dev version - run: | - versionFile="pinecone/__version__" - currentDate=$(date +%Y%m%d%H%M%S) - versionNumber=$(cat $versionFile) - devVersion="${versionNumber}.${currentDate}.spruce" - echo "$devVersion" > $versionFile - - - name: Adjust module name - run: | - sed -i 's/pinecone-client/pinecone-client-spruce/g' pyproject.toml - - - name: Update README - run: | - echo "This is Spruce build of the Pinecone Python client. It is not intended for production use." > README.md - - - uses: actions/setup-python@v4 - with: - python-version: 3.x - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - - - name: Build Python client - run: make package - - - name: Upload Python Spruce client to Test PyPI - env: - TWINE_REPOSITORY: testpypi - PYPI_USERNAME: ${{ secrets.TEST_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} - run: make upload-spruce diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index be68a71ec..3377ca565 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -18,10 +18,6 @@ on: - 'minor' # new features, backwards compatible - 'major' # breaking changes -env: - PYPI_USERNAME: ${{ secrets.TEST_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} - jobs: testing: uses: './.github/workflows/testing.yaml' @@ -37,5 +33,5 @@ jobs: TWINE_REPOSITORY: 'pypi' prereleaseSuffix: '' secrets: - PYPI_USERNAME: ${{ secrets.PROD_PYPI_USERNAME }} - PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PASSWORD }} + PYPI_USERNAME: __token__ + PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PUBLISH_TOKEN }} From 596a9f693f593e48975f5b390eab56ceaf84e8fd Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 5 Jan 2024 11:51:57 -0500 Subject: [PATCH 29/39] Restore __version__ attribute to package (#264) ## Problem `__version__` attribute accidentally got removed in an earlier refactor of the package, but it is still useful when code needs to check what client version they are dealing with. ## Solution - Utils refactoring - Removed `__environment__` and associated code in `pinecone/utils/environment.py` utils, which actually do seem unnecessary. These are only referenced from another util file to define a constant that is also unused. - Migrated remaining code for reading version out of environment.py and into `pinecone/utils/version.py`. This reads a value from `pinecone/__version__` file. The value in this file is automatically updated during the publish workflow. - Update version-adjacent code involved in building the useragent string. Added some simple unit tests to verify these work as expected. - In general, move away from multiple usages of the `get_version()` function in favor of a cached value to avoid unnecessary disk reads. - Exposed `__version__` attribute in top level `__init__.py`. This is what actually makes `pinecone.__version__` work. ### Future todo: - The version number does get aliased to a constant called `CLIENT_VERSION` which seems silly, but I'll leave for now to avoid broadening the scope of this change even further to fix the usages of that constant. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) ## Test Plan Describe specific steps for validating this change. --- pinecone/__environment__ | 0 pinecone/__init__.py | 4 +++- pinecone/utils/__init__.py | 2 +- pinecone/utils/constants.py | 5 ++--- pinecone/utils/user_agent.py | 4 ++-- pinecone/utils/{environment.py => version.py} | 4 +--- tests/unit/test_version.py | 5 +++++ tests/unit/utils/test_user_agent.py | 9 +++++++++ 8 files changed, 23 insertions(+), 10 deletions(-) delete mode 100644 pinecone/__environment__ rename pinecone/utils/{environment.py => version.py} (53%) create mode 100644 tests/unit/test_version.py create mode 100644 tests/unit/utils/test_user_agent.py diff --git a/pinecone/__environment__ b/pinecone/__environment__ deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 91d143916..5c1db1d80 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -8,4 +8,6 @@ from .models import * from .core.client.models import ( IndexModel, -) \ No newline at end of file +) + +from .utils import __version__ \ No newline at end of file diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py index 8c2c486a2..cb811e1aa 100644 --- a/pinecone/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -1,5 +1,5 @@ from .check_kwargs import check_kwargs -from .environment import get_version, get_environment +from .version import __version__ from .user_agent import get_user_agent from .deprecation_notice import warn_deprecated from .fix_tuple_length import fix_tuple_length diff --git a/pinecone/utils/constants.py b/pinecone/utils/constants.py index 4b3090a76..0f29331bb 100644 --- a/pinecone/utils/constants.py +++ b/pinecone/utils/constants.py @@ -1,7 +1,7 @@ import os import enum -from .environment import get_environment, get_version +from .version import __version__ MAX_MSG_SIZE = 128 * 1024 * 1024 @@ -23,8 +23,7 @@ class NodeType(str, enum.Enum): MEMORY4X = "MEMORY4X" -PACKAGE_ENVIRONMENT = get_environment() or "development" -CLIENT_VERSION = get_version() +CLIENT_VERSION = __version__ CLIENT_ID = f"python-client-{CLIENT_VERSION}" REQUIRED_VECTOR_FIELDS = {"id", "values"} diff --git a/pinecone/utils/user_agent.py b/pinecone/utils/user_agent.py index 439a7f5d9..9579870b6 100644 --- a/pinecone/utils/user_agent.py +++ b/pinecone/utils/user_agent.py @@ -1,10 +1,10 @@ import requests import urllib3 -from pinecone.utils import get_version +from .version import __version__ def get_user_agent(): - client_id = f"python-client-{get_version()}" + client_id = f"python-client-{__version__}" user_agent_details = {"requests": requests.__version__, "urllib3": urllib3.__version__} user_agent = "{} ({})".format(client_id, ", ".join([f"{k}:{v}" for k, v in user_agent_details.items()])) return user_agent \ No newline at end of file diff --git a/pinecone/utils/environment.py b/pinecone/utils/version.py similarity index 53% rename from pinecone/utils/environment.py rename to pinecone/utils/version.py index d80e868ed..b60a5bc24 100644 --- a/pinecone/utils/environment.py +++ b/pinecone/utils/version.py @@ -3,6 +3,4 @@ def get_version(): return Path(__file__).parent.parent.joinpath("__version__").read_text().strip() - -def get_environment(): - return Path(__file__).parent.parent.joinpath("__environment__").read_text().strip() \ No newline at end of file +__version__ = get_version() \ No newline at end of file diff --git a/tests/unit/test_version.py b/tests/unit/test_version.py new file mode 100644 index 000000000..99f7cafc2 --- /dev/null +++ b/tests/unit/test_version.py @@ -0,0 +1,5 @@ +import re +import pinecone + +def test_version(): + assert re.search(r"\d+\.\d+\.\d+", pinecone.__version__) is not None \ No newline at end of file diff --git a/tests/unit/utils/test_user_agent.py b/tests/unit/utils/test_user_agent.py new file mode 100644 index 000000000..09525d9a7 --- /dev/null +++ b/tests/unit/utils/test_user_agent.py @@ -0,0 +1,9 @@ +import re +from pinecone.utils.user_agent import get_user_agent + +class TestUserAgent(): + def test_user_agent(self): + useragent = get_user_agent() + assert re.search(r"python-client-\d+\.\d+\.\d+", useragent) is not None + assert re.search(r"requests:\d+\.\d+\.\d+", useragent) is not None + assert re.search(r"urllib3:\d+\.\d+\.\d+", useragent) is not None \ No newline at end of file From a858f52af8f269789c113d0b4415844ad36b9e4a Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Mon, 8 Jan 2024 12:53:52 -0500 Subject: [PATCH 30/39] Accept host urls both with and without https prefix (#265) ## Problem We want to make the client flexible enough to accept data plane host values both with and without the `https://` prefix. This is needed because the value is not prefixed with `https` in the describe_index response, but parts of the UI show the complete url with protocol. ## Solution Add a new util method to normalize the urls. Incorporate the util into the IndexHostStore and ConfigBuilder. The ConfigBuilder usage should cover both the `Index` and `IndexGRPC` milestones. ## Type of Change - [x] New feature (non-breaking change which adds functionality) ## Test Plan Added new unit tests of util. --- pinecone/config/config.py | 4 ++-- pinecone/control/index_host_store.py | 3 ++- pinecone/utils/__init__.py | 3 ++- pinecone/utils/normalize_host.py | 8 ++++++++ tests/unit/test_config.py | 10 +++++----- tests/unit/test_control.py | 2 +- tests/unit/utils/test_normalize_host.py | 18 ++++++++++++++++++ 7 files changed, 38 insertions(+), 10 deletions(-) create mode 100644 pinecone/utils/normalize_host.py create mode 100644 tests/unit/utils/test_normalize_host.py diff --git a/pinecone/config/config.py b/pinecone/config/config.py index 92d7a7767..9f6224292 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -4,14 +4,13 @@ from pinecone.exceptions import PineconeConfigurationError from pinecone.config.openapi import OpenApiConfigFactory from pinecone.core.client.configuration import Configuration as OpenApiConfiguration - +from pinecone.utils import normalize_host class Config(NamedTuple): api_key: str = "" host: str = "" openapi_config: Optional[OpenApiConfiguration] = None additional_headers: Optional[Dict[str, str]] = {} - class ConfigBuilder: """ @@ -40,6 +39,7 @@ def build( ) -> Config: api_key = api_key or kwargs.pop("api_key", None) or os.getenv("PINECONE_API_KEY") host = host or kwargs.pop("host", None) + host = normalize_host(host) if not api_key: raise PineconeConfigurationError("You haven't specified an Api-Key.") diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index 69e98bf91..7a5622e62 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -2,6 +2,7 @@ from pinecone.config import Config from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi from pinecone.core.client.exceptions import PineconeException +from pinecone.utils import normalize_host class SingletonMeta(type): _instances: Dict[str, str] = {} @@ -31,7 +32,7 @@ def key_exists(self, key: str) -> bool: def set_host(self, config: Config, index_name: str, host: str): if host: key = self._key(config, index_name) - self._indexHosts[key] = "https://" + host + self._indexHosts[key] = normalize_host(host) def get_host(self, api: IndexOperationsApi, config: Config, index_name: str) -> str: key = self._key(config, index_name) diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py index cb811e1aa..e4ce28b66 100644 --- a/pinecone/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -3,4 +3,5 @@ from .user_agent import get_user_agent from .deprecation_notice import warn_deprecated from .fix_tuple_length import fix_tuple_length -from .convert_to_list import convert_to_list \ No newline at end of file +from .convert_to_list import convert_to_list +from .normalize_host import normalize_host \ No newline at end of file diff --git a/pinecone/utils/normalize_host.py b/pinecone/utils/normalize_host.py new file mode 100644 index 000000000..2eac61a1c --- /dev/null +++ b/pinecone/utils/normalize_host.py @@ -0,0 +1,8 @@ +def normalize_host(host): + if host is None: + return host + if host.startswith('https://'): + return host + if host.startswith('http://'): + return host + return 'https://' + host \ No newline at end of file diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 058e6091d..39ccd6cd5 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -28,16 +28,16 @@ def run_before_and_after_tests(tmpdir): def test_init_with_environment_vars(self): os.environ["PINECONE_API_KEY"] = "test-api-key" - os.environ["PINECONE_CONTROLLER_HOST"] = "test-controller-host" + os.environ["PINECONE_CONTROLLER_HOST"] = "https://test-controller-host" config = PineconeConfig.build() assert config.api_key == "test-api-key" - assert config.host == "test-controller-host" + assert config.host == "https://test-controller-host" def test_init_with_positional_args(self): api_key = "my-api-key" - host = "my-controller-host" + host = "https://my-controller-host" config = PineconeConfig.build(api_key, host) @@ -52,7 +52,7 @@ def test_init_with_kwargs(self): config = PineconeConfig.build(api_key=api_key, host=controller_host, openapi_config=openapi_config) assert config.api_key == api_key - assert config.host == controller_host + assert config.host == 'https://' + controller_host assert config.openapi_config == openapi_config def test_resolution_order_kwargs_over_env_vars(self): @@ -69,7 +69,7 @@ def test_resolution_order_kwargs_over_env_vars(self): config = PineconeConfig.build(api_key=api_key, host=controller_host) assert config.api_key == api_key - assert config.host == controller_host + assert config.host == 'https://' + controller_host def test_errors_when_no_api_key_is_present(self): with pytest.raises(PineconeConfigurationError): diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 6a1ab8180..650f6d9d4 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -19,7 +19,7 @@ def test_default_host(self): def test_passing_host(self): p = Pinecone(api_key="123-456-789", host="my-host") - assert p.index_api.api_client.configuration.host == "my-host" + assert p.index_api.api_client.configuration.host == "https://my-host" def test_passing_additional_headers(self): extras = {"header1": "my-value", "header2": "my-value2"} diff --git a/tests/unit/utils/test_normalize_host.py b/tests/unit/utils/test_normalize_host.py new file mode 100644 index 000000000..b5a54876d --- /dev/null +++ b/tests/unit/utils/test_normalize_host.py @@ -0,0 +1,18 @@ +from pinecone.utils import normalize_host + +def test_when_url_is_none(): + assert normalize_host(None) is None + +def test_when_url_is_https(): + assert normalize_host('https://index-name-abcdef.svc.pinecone.io') == 'https://index-name-abcdef.svc.pinecone.io' + +def test_when_url_is_http(): + # This should not occur in prod, but if it does, we will leave it alone. + # Could be useful when testing with local proxies. + assert normalize_host('http://index-name-abcdef.svc.pinecone.io') == 'http://index-name-abcdef.svc.pinecone.io' + +def test_when_url_is_host_without_protocol(): + assert normalize_host('index-name-abcdef.svc.pinecone.io') == 'https://index-name-abcdef.svc.pinecone.io' + +def test_can_be_called_multiple_times(): + assert normalize_host(normalize_host('index-name-abcdef.svc.pinecone.io')) == 'https://index-name-abcdef.svc.pinecone.io' \ No newline at end of file From 257ae2530e50e452098b225a41ccb395847b46cf Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 9 Jan 2024 19:26:53 -0500 Subject: [PATCH 31/39] Dependency testing, support python3.8, downgrade urllib3 (#263) ## Problem Some goals: - Verify our code works with the claimed dependency ranges - Bring back python 3.8 support for LlamaIndex compatibility - Add flexibility to urllib3 dependency version by extending the version range back to 1.26.x. ## Solution - Remove more unused dependencies - `requests` (not sure when this was added; doesn't seem like it's been used for a while) - `python-dateutil` (no longer needed now that we've removed some date parsing default behavior in the generated client code) - Specify python-version specific dependency configuration for some dev dependencies (numpy, pandas-stubs) that were pushing us toward dropping py3.8 support - Added new reusable workflow action, `.github/actions/create-index/`, to create an index that will be used for subsequent testing. - Add new test workflow jobs, `dependency-matrix-rest` and `dependency-matrix-grpc`, with minimal integration test to verify the package works with different combinations of installed python dependencies. - New tests stored under `tests/dependency` - Integration test exercises control plane (list indexes, describe an index ) and data plane (upsert and query). It does not create a new index for each test as this is time-consuming, the test matrix is large, and index creation is extensively tested elsewhere. - Test configuration was getting unwieldy, so I split `testing.yaml` into `testing-rest.yaml` and `testing-grpc.yaml` - Data freshness isn't a huge issue for these tests, since the index is reused for upsert/query across different configurations. It's sufficient for these minimal tests to issue network calls and get responses without throwing exceptions to verify the dependencies are working. ## Type of Change Is "being able to install" a feature? - [x] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) ## Test Plan Add new test matrix to verify some dependencies work across the claimed range. --- .github/actions/create-index/action.yml | 55 ++++ .github/actions/delete-index/action.yml | 29 ++ .github/actions/setup-poetry/action.yml | 28 +- .github/workflows/pr.yaml | 25 +- .github/workflows/testing-grpc.yaml | 128 ++++++++ .../{testing.yaml => testing-rest.yaml} | 90 +++--- pinecone/config/openapi.py | 1 - pinecone/utils/user_agent.py | 3 +- poetry.lock | 274 +++++++++++------- pyproject.toml | 47 +-- scripts/create.py | 37 +++ scripts/delete.py | 17 ++ tests/dependency/grpc/test_sanity.py | 45 +++ tests/dependency/rest/test_sanity.py | 45 +++ tests/integration/conftest.py | 11 +- tests/unit/utils/test_user_agent.py | 1 - 16 files changed, 654 insertions(+), 182 deletions(-) create mode 100644 .github/actions/create-index/action.yml create mode 100644 .github/actions/delete-index/action.yml create mode 100644 .github/workflows/testing-grpc.yaml rename .github/workflows/{testing.yaml => testing-rest.yaml} (67%) create mode 100644 scripts/create.py create mode 100644 scripts/delete.py create mode 100644 tests/dependency/grpc/test_sanity.py create mode 100644 tests/dependency/rest/test_sanity.py diff --git a/.github/actions/create-index/action.yml b/.github/actions/create-index/action.yml new file mode 100644 index 000000000..79b061d90 --- /dev/null +++ b/.github/actions/create-index/action.yml @@ -0,0 +1,55 @@ +name: 'Create Index' +description: 'Creates an index to be used in other tests' + +inputs: + region: + description: 'The region of the index' + required: false + default: 'us-west-2' + cloud: + description: 'The cloud of the index' + required: false + default: 'aws' + name_prefix: + description: 'The prefix of the index name' + required: false + default: 'index-name' + dimension: + description: 'The dimension of the index' + required: false + default: '3' + metric: + description: 'The metric of the index' + required: false + default: 'cosine' + PINECONE_API_KEY: + description: 'The Pinecone API key' + required: true + +outputs: + index_name: + description: 'The name of the index, including randomized suffix' + value: ${{ steps.create-index.outputs.index_name }} + +runs: + using: 'composite' + steps: + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + + - name: Create index + id: create-index + shell: bash + run: poetry run python3 scripts/create.py + env: + PINECONE_API_KEY: ${{ inputs.PINECONE_API_KEY }} + NAME_PREFIX: ${{ inputs.name_prefix }} + REGION: ${{ inputs.region }} + CLOUD: ${{ inputs.cloud }} + DIMENSION: ${{ inputs.dimension }} + METRIC: ${{ inputs.metric }} diff --git a/.github/actions/delete-index/action.yml b/.github/actions/delete-index/action.yml new file mode 100644 index 000000000..2146ae6ab --- /dev/null +++ b/.github/actions/delete-index/action.yml @@ -0,0 +1,29 @@ +name: 'Delete Index' +description: 'Deletes an index to be used in other tests' + +inputs: + index_name: + description: 'The name of the index to delete' + required: true + PINECONE_API_KEY: + description: 'The Pinecone API key' + required: true + + +runs: + using: 'composite' + steps: + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + + - name: Delete index + shell: bash + run: poetry run python3 scripts/delete.py + env: + PINECONE_API_KEY: ${{ inputs.PINECONE_API_KEY }} + INDEX_NAME: ${{ inputs.index_name }} \ No newline at end of file diff --git a/.github/actions/setup-poetry/action.yml b/.github/actions/setup-poetry/action.yml index a60b6a1c2..19e47e43e 100644 --- a/.github/actions/setup-poetry/action.yml +++ b/.github/actions/setup-poetry/action.yml @@ -5,6 +5,14 @@ inputs: description: 'Install gRPC dependencies' required: true default: 'false' + include_dev: + description: 'Install dev dependencies' + required: true + default: 'true' + include_types: + description: 'Install typing dependencies (mypy, type stubs, etc)' + required: true + default: 'true' runs: using: 'composite' @@ -13,17 +21,13 @@ runs: uses: snok/install-poetry@v1 - name: Install dependencies - if: ${{ inputs.include_grpc == 'false' }} - shell: bash - run: | - poetry install - - # We separate the gRPC dependencies from the REST client's install - # behavior, so we test installing the grpc dependencies here as well - # The dependencies that are specific to gRPC are defined in pyproject.toml - # under tool.poetry.extras - - name: Install gRPC dependencies - if: ${{ inputs.include_grpc == 'true' }} shell: bash + env: + INCLUDE_GRPC: ${{ inputs.include_grpc }} + INCLUDE_DEV: ${{ inputs.include_dev }} + INCLUDE_TYPES: ${{ inputs.include_types }} run: | - poetry install --extras "grpc" + GRPC_FLAG=$( [ "$INCLUDE_GRPC" = "true" ] && echo "--extras grpc" || echo "" ) + DEV_FLAG=$( [ "$INCLUDE_DEV" = "false" ] && echo "--without dev" || echo "" ) + TYPING_FLAG=$( [ "$INCLUDE_TYPES" = "true" ] && echo "--with types" || echo "" ) + poetry install $DEV_FLAG $TYPING_FLAG $GRPC_FLAG \ No newline at end of file diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 936952fdf..f48f7f5cb 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -8,9 +8,30 @@ on: workflow_dispatch: {} jobs: - run-tests: - uses: './.github/workflows/testing.yaml' + run-tests-rest: + uses: './.github/workflows/testing-rest.yaml' secrets: inherit + run-tests-grpc: + uses: './.github/workflows/testing-grpc.yaml' + secrets: inherit + package: + name: Check packaging + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8, 3.9, '3.10', 3.11] + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + - name: Package + run: poetry build + + build-docs: name: Build docs with pdoc diff --git a/.github/workflows/testing-grpc.yaml b/.github/workflows/testing-grpc.yaml new file mode 100644 index 000000000..06ef24af5 --- /dev/null +++ b/.github/workflows/testing-grpc.yaml @@ -0,0 +1,128 @@ +name: Testing GRPC + +on: + workflow_call: {} + +jobs: + units-grpc: + name: Unit tests (GRPC) + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8, 3.9, '3.10', 3.11] + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: true + + - name: Run unit tests (GRPC) + run: poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc + + - name: mypy check + run: | + # Still lots of errors when running on the whole package (especially + # in the generated core module), but we can check these subpackages + # so we don't add new regressions. + poetry run mypy pinecone --exclude pinecone/core + + dependency-matrix-grpc-setup: + name: Deps setup (GRPC) + runs-on: ubuntu-latest + outputs: + index_name: ${{ steps.setup-index.outputs.index_name }} + steps: + - uses: actions/checkout@v4 + - name: Create index + id: setup-index + uses: ./.github/actions/create-index + timeout-minutes: 5 + with: + name_prefix: depstest-grpc-${{ github.run_number }} + dimension: 2 + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} + + dependency-matrix-grpc: + name: Deps (GRPC) + needs: dependency-matrix-grpc-setup + runs-on: ubuntu-latest + strategy: + max-parallel: 5 + fail-fast: false + matrix: + python-version: + - 3.8 + # - 3.9 + # - "3.10" + # - 3.11 + grpcio-version: + - 1.44.0 + # - 1.46.5 + # - 1.47.5 + # - 1.48.2 + # - 1.49.1 + - 1.50.0 + # - 1.51.3 + # - 1.53.2 + # - 1.54.3 + # - 1.55.3 + - 1.56.2 + # - 1.57.0 + # - 1.58.0 + # - 1.59.3 + - 1.60.0 + lz4-version: + - 3.1.3 + # - 3.1.10 + - 4.0.0 + # - 4.0.1 + # - 4.1.0 + - 4.3.3 + protobuf-version: + - 3.20.3 + googleapis-common-protos-version: + - 1.53.0 + - 1.62.0 + grpc-gateway-protoc-gen-openapiv2-version: + - 0.1.0 + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: true + include_types: false + - name: Install grpcio ${{ matrix.grpcio-version }} + run: poetry add grpcio==${{ matrix.grpcio-version }} + - name: Install lz4 ${{ matrix.lz4-version }} + run: poetry add lz4==${{ matrix.lz4-version }} + - name: Install protobuf ${{ matrix.protobuf-version }} + run: poetry add protobuf==${{ matrix.protobuf-version }} + - name: Install googleapis-common-protos ${{ matrix.googleapis-common-protos-version }} + run: poetry add googleapis-common-protos==${{ matrix.googleapis-common-protos-version }} + + - uses: nick-fields/retry@v2 + with: + timeout_minutes: 5 + max_attempts: 3 + retry_on: error + command: poetry run pytest tests/dependency/grpc -s -v + env: + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} + INDEX_NAME: ${{ needs.dependency-matrix-grpc-setup.outputs.index_name }} + \ No newline at end of file diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing-rest.yaml similarity index 67% rename from .github/workflows/testing.yaml rename to .github/workflows/testing-rest.yaml index 1306bf3bf..31e9dadfb 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing-rest.yaml @@ -1,10 +1,11 @@ -name: Testing +name: Testing REST on: workflow_call: {} + jobs: - units-no-grpc: + units-rest: name: Unit tests (REST) runs-on: ubuntu-latest strategy: @@ -66,7 +67,7 @@ jobs: env: PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.python-version}}" + GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.testConfig.python-version}}" POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} @@ -77,49 +78,55 @@ jobs: env: PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY_STAGING }} - GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.python-version}}" + GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.testConfig.python-version}}" POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} - units-grpc: - name: Unit tests (GRPC) + dependency-matrix-rest-setup: + name: Deps setup (REST) runs-on: ubuntu-latest - strategy: - matrix: - python-version: [3.8, 3.9, '3.10', 3.11] - + outputs: + index_name: ${{ steps.setup-index-rest.outputs.index_name }} steps: - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + - name: Create index + id: setup-index-rest + uses: ./.github/actions/create-index + timeout-minutes: 5 with: - python-version: ${{ matrix.python-version }} - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - with: - include_grpc: true - - - name: Run unit tests (GRPC) - run: poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc - - - name: mypy check - run: | - # Still lots of errors when running on the whole package (especially - # in the generated core module), but we can check these subpackages - # so we don't add new regressions. - poetry run mypy pinecone --exclude pinecone/core + name_prefix: depstest-rest-${{ github.run_number }} + dimension: 2 + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - package: - name: Check packaging + dependency-matrix-rest: + name: Deps (REST) runs-on: ubuntu-latest + needs: dependency-matrix-rest-setup strategy: + max-parallel: 5 + fail-fast: false matrix: - python-version: [3.8, 3.9, '3.10', 3.11] - + python-version: + - 3.8 + - 3.9 + - "3.10" + - 3.11 + # Poetry doesn't yet work with 3.12 & 3.13 + # - 3.12 + # - 3.13 + urllib3-version: + - 1.26.16 + - 1.26.18 + - 2.0.2 + - 2.0.5 + - 2.1.0 + # - 1.26.17 + # - 2.0.3 + # - 2.0.4 + # - 2.0.6 + # - 2.0.7 steps: - uses: actions/checkout@v4 @@ -130,6 +137,19 @@ jobs: - name: Setup Poetry uses: ./.github/actions/setup-poetry + with: + include_grpc: false + include_types: false + + - name: Install urllib3 ${{ matrix.urllib3-version }} + run: poetry add urllib3==${{ matrix.urllib3-version }} - - name: Package - run: poetry build + - uses: nick-fields/retry@v2 + with: + timeout_minutes: 5 + max_attempts: 3 + retry_on: error + command: poetry run pytest tests/dependency/rest -s -v + env: + PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} + INDEX_NAME: ${{ needs.dependency-matrix-rest-setup.outputs.index_name }} \ No newline at end of file diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index cca504bc1..6c6c3c058 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -2,7 +2,6 @@ from typing import List, Optional import certifi -import requests import socket from urllib3.connection import HTTPConnection diff --git a/pinecone/utils/user_agent.py b/pinecone/utils/user_agent.py index 9579870b6..5fd23a8c6 100644 --- a/pinecone/utils/user_agent.py +++ b/pinecone/utils/user_agent.py @@ -1,10 +1,9 @@ -import requests import urllib3 from .version import __version__ def get_user_agent(): client_id = f"python-client-{__version__}" - user_agent_details = {"requests": requests.__version__, "urllib3": urllib3.__version__} + user_agent_details = {"urllib3": urllib3.__version__} user_agent = "{} ({})".format(client_id, ", ".join([f"{k}:{v}" for k, v in user_agent_details.items()])) return user_agent \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index 1aa020069..ebcb3b4e3 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,5 +1,20 @@ # This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. +[[package]] +name = "astunparse" +version = "1.6.3" +description = "An AST unparser for Python" +optional = false +python-versions = "*" +files = [ + {file = "astunparse-1.6.3-py2.py3-none-any.whl", hash = "sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8"}, + {file = "astunparse-1.6.3.tar.gz", hash = "sha256:5ad93a8456f0d084c3456d059fd9a92cce667963232cbf763eac3bc5b7940872"}, +] + +[package.dependencies] +six = ">=1.6.1,<2.0" +wheel = ">=0.23.0,<1.0" + [[package]] name = "attrs" version = "23.1.0" @@ -544,43 +559,84 @@ files = [ [[package]] name = "numpy" -version = "1.26.1" +version = "1.24.4" description = "Fundamental package for array computing in Python" optional = false -python-versions = "<3.13,>=3.9" +python-versions = ">=3.8" files = [ - {file = "numpy-1.26.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:82e871307a6331b5f09efda3c22e03c095d957f04bf6bc1804f30048d0e5e7af"}, - {file = "numpy-1.26.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cdd9ec98f0063d93baeb01aad472a1a0840dee302842a2746a7a8e92968f9575"}, - {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d78f269e0c4fd365fc2992c00353e4530d274ba68f15e968d8bc3c69ce5f5244"}, - {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8ab9163ca8aeb7fd32fe93866490654d2f7dda4e61bc6297bf72ce07fdc02f67"}, - {file = "numpy-1.26.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:78ca54b2f9daffa5f323f34cdf21e1d9779a54073f0018a3094ab907938331a2"}, - {file = "numpy-1.26.1-cp310-cp310-win32.whl", hash = "sha256:d1cfc92db6af1fd37a7bb58e55c8383b4aa1ba23d012bdbba26b4bcca45ac297"}, - {file = "numpy-1.26.1-cp310-cp310-win_amd64.whl", hash = "sha256:d2984cb6caaf05294b8466966627e80bf6c7afd273279077679cb010acb0e5ab"}, - {file = "numpy-1.26.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cd7837b2b734ca72959a1caf3309457a318c934abef7a43a14bb984e574bbb9a"}, - {file = "numpy-1.26.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1c59c046c31a43310ad0199d6299e59f57a289e22f0f36951ced1c9eac3665b9"}, - {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d58e8c51a7cf43090d124d5073bc29ab2755822181fcad978b12e144e5e5a4b3"}, - {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6081aed64714a18c72b168a9276095ef9155dd7888b9e74b5987808f0dd0a974"}, - {file = "numpy-1.26.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:97e5d6a9f0702c2863aaabf19f0d1b6c2628fbe476438ce0b5ce06e83085064c"}, - {file = "numpy-1.26.1-cp311-cp311-win32.whl", hash = "sha256:b9d45d1dbb9de84894cc50efece5b09939752a2d75aab3a8b0cef6f3a35ecd6b"}, - {file = "numpy-1.26.1-cp311-cp311-win_amd64.whl", hash = "sha256:3649d566e2fc067597125428db15d60eb42a4e0897fc48d28cb75dc2e0454e53"}, - {file = "numpy-1.26.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1d1bd82d539607951cac963388534da3b7ea0e18b149a53cf883d8f699178c0f"}, - {file = "numpy-1.26.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:afd5ced4e5a96dac6725daeb5242a35494243f2239244fad10a90ce58b071d24"}, - {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a03fb25610ef560a6201ff06df4f8105292ba56e7cdd196ea350d123fc32e24e"}, - {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dcfaf015b79d1f9f9c9fd0731a907407dc3e45769262d657d754c3a028586124"}, - {file = "numpy-1.26.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e509cbc488c735b43b5ffea175235cec24bbc57b227ef1acc691725beb230d1c"}, - {file = "numpy-1.26.1-cp312-cp312-win32.whl", hash = "sha256:af22f3d8e228d84d1c0c44c1fbdeb80f97a15a0abe4f080960393a00db733b66"}, - {file = "numpy-1.26.1-cp312-cp312-win_amd64.whl", hash = "sha256:9f42284ebf91bdf32fafac29d29d4c07e5e9d1af862ea73686581773ef9e73a7"}, - {file = "numpy-1.26.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bb894accfd16b867d8643fc2ba6c8617c78ba2828051e9a69511644ce86ce83e"}, - {file = "numpy-1.26.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e44ccb93f30c75dfc0c3aa3ce38f33486a75ec9abadabd4e59f114994a9c4617"}, - {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9696aa2e35cc41e398a6d42d147cf326f8f9d81befcb399bc1ed7ffea339b64e"}, - {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b411040beead47a228bde3b2241100454a6abde9df139ed087bd73fc0a4908"}, - {file = "numpy-1.26.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1e11668d6f756ca5ef534b5be8653d16c5352cbb210a5c2a79ff288e937010d5"}, - {file = "numpy-1.26.1-cp39-cp39-win32.whl", hash = "sha256:d1d2c6b7dd618c41e202c59c1413ef9b2c8e8a15f5039e344af64195459e3104"}, - {file = "numpy-1.26.1-cp39-cp39-win_amd64.whl", hash = "sha256:59227c981d43425ca5e5c01094d59eb14e8772ce6975d4b2fc1e106a833d5ae2"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:06934e1a22c54636a059215d6da99e23286424f316fddd979f5071093b648668"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76ff661a867d9272cd2a99eed002470f46dbe0943a5ffd140f49be84f68ffc42"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:6965888d65d2848e8768824ca8288db0a81263c1efccec881cb35a0d805fcd2f"}, - {file = "numpy-1.26.1.tar.gz", hash = "sha256:c8c6c72d4a9f831f328efb1312642a1cafafaa88981d9ab76368d50d07d93cbe"}, + {file = "numpy-1.24.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c0bfb52d2169d58c1cdb8cc1f16989101639b34c7d3ce60ed70b19c63eba0b64"}, + {file = "numpy-1.24.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ed094d4f0c177b1b8e7aa9cba7d6ceed51c0e569a5318ac0ca9a090680a6a1b1"}, + {file = "numpy-1.24.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79fc682a374c4a8ed08b331bef9c5f582585d1048fa6d80bc6c35bc384eee9b4"}, + {file = "numpy-1.24.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7ffe43c74893dbf38c2b0a1f5428760a1a9c98285553c89e12d70a96a7f3a4d6"}, + {file = "numpy-1.24.4-cp310-cp310-win32.whl", hash = "sha256:4c21decb6ea94057331e111a5bed9a79d335658c27ce2adb580fb4d54f2ad9bc"}, + {file = "numpy-1.24.4-cp310-cp310-win_amd64.whl", hash = "sha256:b4bea75e47d9586d31e892a7401f76e909712a0fd510f58f5337bea9572c571e"}, + {file = "numpy-1.24.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f136bab9c2cfd8da131132c2cf6cc27331dd6fae65f95f69dcd4ae3c3639c810"}, + {file = "numpy-1.24.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e2926dac25b313635e4d6cf4dc4e51c8c0ebfed60b801c799ffc4c32bf3d1254"}, + {file = "numpy-1.24.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:222e40d0e2548690405b0b3c7b21d1169117391c2e82c378467ef9ab4c8f0da7"}, + {file = "numpy-1.24.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7215847ce88a85ce39baf9e89070cb860c98fdddacbaa6c0da3ffb31b3350bd5"}, + {file = "numpy-1.24.4-cp311-cp311-win32.whl", hash = "sha256:4979217d7de511a8d57f4b4b5b2b965f707768440c17cb70fbf254c4b225238d"}, + {file = "numpy-1.24.4-cp311-cp311-win_amd64.whl", hash = "sha256:b7b1fc9864d7d39e28f41d089bfd6353cb5f27ecd9905348c24187a768c79694"}, + {file = "numpy-1.24.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1452241c290f3e2a312c137a9999cdbf63f78864d63c79039bda65ee86943f61"}, + {file = "numpy-1.24.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:04640dab83f7c6c85abf9cd729c5b65f1ebd0ccf9de90b270cd61935eef0197f"}, + {file = "numpy-1.24.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5425b114831d1e77e4b5d812b69d11d962e104095a5b9c3b641a218abcc050e"}, + {file = "numpy-1.24.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd80e219fd4c71fc3699fc1dadac5dcf4fd882bfc6f7ec53d30fa197b8ee22dc"}, + {file = "numpy-1.24.4-cp38-cp38-win32.whl", hash = "sha256:4602244f345453db537be5314d3983dbf5834a9701b7723ec28923e2889e0bb2"}, + {file = "numpy-1.24.4-cp38-cp38-win_amd64.whl", hash = "sha256:692f2e0f55794943c5bfff12b3f56f99af76f902fc47487bdfe97856de51a706"}, + {file = "numpy-1.24.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2541312fbf09977f3b3ad449c4e5f4bb55d0dbf79226d7724211acc905049400"}, + {file = "numpy-1.24.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:9667575fb6d13c95f1b36aca12c5ee3356bf001b714fc354eb5465ce1609e62f"}, + {file = "numpy-1.24.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f3a86ed21e4f87050382c7bc96571755193c4c1392490744ac73d660e8f564a9"}, + {file = "numpy-1.24.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d11efb4dbecbdf22508d55e48d9c8384db795e1b7b51ea735289ff96613ff74d"}, + {file = "numpy-1.24.4-cp39-cp39-win32.whl", hash = "sha256:6620c0acd41dbcb368610bb2f4d83145674040025e5536954782467100aa8835"}, + {file = "numpy-1.24.4-cp39-cp39-win_amd64.whl", hash = "sha256:befe2bf740fd8373cf56149a5c23a0f601e82869598d41f8e188a0e9869926f8"}, + {file = "numpy-1.24.4-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:31f13e25b4e304632a4619d0e0777662c2ffea99fcae2029556b17d8ff958aef"}, + {file = "numpy-1.24.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95f7ac6540e95bc440ad77f56e520da5bf877f87dca58bd095288dce8940532a"}, + {file = "numpy-1.24.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:e98f220aa76ca2a977fe435f5b04d7b3470c0a2e6312907b37ba6068f26787f2"}, + {file = "numpy-1.24.4.tar.gz", hash = "sha256:80f5e3a4e498641401868df4208b74581206afbee7cf7b8329daae82676d9463"}, +] + +[[package]] +name = "numpy" +version = "1.26.3" +description = "Fundamental package for array computing in Python" +optional = false +python-versions = ">=3.9" +files = [ + {file = "numpy-1.26.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:806dd64230dbbfaca8a27faa64e2f414bf1c6622ab78cc4264f7f5f028fee3bf"}, + {file = "numpy-1.26.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02f98011ba4ab17f46f80f7f8f1c291ee7d855fcef0a5a98db80767a468c85cd"}, + {file = "numpy-1.26.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6d45b3ec2faed4baca41c76617fcdcfa4f684ff7a151ce6fc78ad3b6e85af0a6"}, + {file = "numpy-1.26.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bdd2b45bf079d9ad90377048e2747a0c82351989a2165821f0c96831b4a2a54b"}, + {file = "numpy-1.26.3-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:211ddd1e94817ed2d175b60b6374120244a4dd2287f4ece45d49228b4d529178"}, + {file = "numpy-1.26.3-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b1240f767f69d7c4c8a29adde2310b871153df9b26b5cb2b54a561ac85146485"}, + {file = "numpy-1.26.3-cp310-cp310-win32.whl", hash = "sha256:21a9484e75ad018974a2fdaa216524d64ed4212e418e0a551a2d83403b0531d3"}, + {file = "numpy-1.26.3-cp310-cp310-win_amd64.whl", hash = "sha256:9e1591f6ae98bcfac2a4bbf9221c0b92ab49762228f38287f6eeb5f3f55905ce"}, + {file = "numpy-1.26.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b831295e5472954104ecb46cd98c08b98b49c69fdb7040483aff799a755a7374"}, + {file = "numpy-1.26.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9e87562b91f68dd8b1c39149d0323b42e0082db7ddb8e934ab4c292094d575d6"}, + {file = "numpy-1.26.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c66d6fec467e8c0f975818c1796d25c53521124b7cfb760114be0abad53a0a2"}, + {file = "numpy-1.26.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f25e2811a9c932e43943a2615e65fc487a0b6b49218899e62e426e7f0a57eeda"}, + {file = "numpy-1.26.3-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:af36e0aa45e25c9f57bf684b1175e59ea05d9a7d3e8e87b7ae1a1da246f2767e"}, + {file = "numpy-1.26.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:51c7f1b344f302067b02e0f5b5d2daa9ed4a721cf49f070280ac202738ea7f00"}, + {file = "numpy-1.26.3-cp311-cp311-win32.whl", hash = "sha256:7ca4f24341df071877849eb2034948459ce3a07915c2734f1abb4018d9c49d7b"}, + {file = "numpy-1.26.3-cp311-cp311-win_amd64.whl", hash = "sha256:39763aee6dfdd4878032361b30b2b12593fb445ddb66bbac802e2113eb8a6ac4"}, + {file = "numpy-1.26.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:a7081fd19a6d573e1a05e600c82a1c421011db7935ed0d5c483e9dd96b99cf13"}, + {file = "numpy-1.26.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:12c70ac274b32bc00c7f61b515126c9205323703abb99cd41836e8125ea0043e"}, + {file = "numpy-1.26.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f784e13e598e9594750b2ef6729bcd5a47f6cfe4a12cca13def35e06d8163e3"}, + {file = "numpy-1.26.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5f24750ef94d56ce6e33e4019a8a4d68cfdb1ef661a52cdaee628a56d2437419"}, + {file = "numpy-1.26.3-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:77810ef29e0fb1d289d225cabb9ee6cf4d11978a00bb99f7f8ec2132a84e0166"}, + {file = "numpy-1.26.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8ed07a90f5450d99dad60d3799f9c03c6566709bd53b497eb9ccad9a55867f36"}, + {file = "numpy-1.26.3-cp312-cp312-win32.whl", hash = "sha256:f73497e8c38295aaa4741bdfa4fda1a5aedda5473074369eca10626835445511"}, + {file = "numpy-1.26.3-cp312-cp312-win_amd64.whl", hash = "sha256:da4b0c6c699a0ad73c810736303f7fbae483bcb012e38d7eb06a5e3b432c981b"}, + {file = "numpy-1.26.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1666f634cb3c80ccbd77ec97bc17337718f56d6658acf5d3b906ca03e90ce87f"}, + {file = "numpy-1.26.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:18c3319a7d39b2c6a9e3bb75aab2304ab79a811ac0168a671a62e6346c29b03f"}, + {file = "numpy-1.26.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0b7e807d6888da0db6e7e75838444d62495e2b588b99e90dd80c3459594e857b"}, + {file = "numpy-1.26.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b4d362e17bcb0011738c2d83e0a65ea8ce627057b2fdda37678f4374a382a137"}, + {file = "numpy-1.26.3-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:b8c275f0ae90069496068c714387b4a0eba5d531aace269559ff2b43655edd58"}, + {file = "numpy-1.26.3-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:cc0743f0302b94f397a4a65a660d4cd24267439eb16493fb3caad2e4389bccbb"}, + {file = "numpy-1.26.3-cp39-cp39-win32.whl", hash = "sha256:9bc6d1a7f8cedd519c4b7b1156d98e051b726bf160715b769106661d567b3f03"}, + {file = "numpy-1.26.3-cp39-cp39-win_amd64.whl", hash = "sha256:867e3644e208c8922a3be26fc6bbf112a035f50f0a86497f98f228c50c607bb2"}, + {file = "numpy-1.26.3-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:3c67423b3703f8fbd90f5adaa37f85b5794d3366948efe9a5190a5f3a83fc34e"}, + {file = "numpy-1.26.3-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:46f47ee566d98849323f01b349d58f2557f02167ee301e5e28809a8c0e27a2d0"}, + {file = "numpy-1.26.3-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a8474703bffc65ca15853d5fd4d06b18138ae90c17c8d12169968e998e448bb5"}, + {file = "numpy-1.26.3.tar.gz", hash = "sha256:697df43e2b6310ecc9d95f05d5ef20eacc09c7c4ecc9da3f235d39e71b7da1e4"}, ] [[package]] @@ -596,81 +652,94 @@ files = [ [[package]] name = "pandas" -version = "2.1.2" +version = "2.0.3" description = "Powerful data structures for data analysis, time series, and statistics" optional = false -python-versions = ">=3.9" +python-versions = ">=3.8" files = [ - {file = "pandas-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:24057459f19db9ebb02984c6fdd164a970b31a95f38e4a49cf7615b36a1b532c"}, - {file = "pandas-2.1.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a6cf8fcc8a63d333970b950a7331a30544cf59b1a97baf0a7409e09eafc1ac38"}, - {file = "pandas-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ae6ffbd9d614c20d028c7117ee911fc4e266b4dca2065d5c5909e401f8ff683"}, - {file = "pandas-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eff794eeb7883c5aefb1ed572e7ff533ae779f6c6277849eab9e77986e352688"}, - {file = "pandas-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:02954e285e8e2f4006b6f22be6f0df1f1c3c97adbb7ed211c6b483426f20d5c8"}, - {file = "pandas-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:5b40c9f494e1f27588c369b9e4a6ca19cd924b3a0e1ef9ef1a8e30a07a438f43"}, - {file = "pandas-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:08d287b68fd28906a94564f15118a7ca8c242e50ae7f8bd91130c362b2108a81"}, - {file = "pandas-2.1.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bbd98dcdcd32f408947afdb3f7434fade6edd408c3077bbce7bd840d654d92c6"}, - {file = "pandas-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e90c95abb3285d06f6e4feedafc134306a8eced93cb78e08cf50e224d5ce22e2"}, - {file = "pandas-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:52867d69a54e71666cd184b04e839cff7dfc8ed0cd6b936995117fdae8790b69"}, - {file = "pandas-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8d0382645ede2fde352da2a885aac28ec37d38587864c0689b4b2361d17b1d4c"}, - {file = "pandas-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:65177d1c519b55e5b7f094c660ed357bb7d86e799686bb71653b8a4803d8ff0d"}, - {file = "pandas-2.1.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5aa6b86802e8cf7716bf4b4b5a3c99b12d34e9c6a9d06dad254447a620437931"}, - {file = "pandas-2.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d594e2ce51b8e0b4074e6644758865dc2bb13fd654450c1eae51201260a539f1"}, - {file = "pandas-2.1.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3223f997b6d2ebf9c010260cf3d889848a93f5d22bb4d14cd32638b3d8bba7ad"}, - {file = "pandas-2.1.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc4944dc004ca6cc701dfa19afb8bdb26ad36b9bed5bcec617d2a11e9cae6902"}, - {file = "pandas-2.1.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3f76280ce8ec216dde336e55b2b82e883401cf466da0fe3be317c03fb8ee7c7d"}, - {file = "pandas-2.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:7ad20d24acf3a0042512b7e8d8fdc2e827126ed519d6bd1ed8e6c14ec8a2c813"}, - {file = "pandas-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:021f09c15e1381e202d95d4a21ece8e7f2bf1388b6d7e9cae09dfe27bd2043d1"}, - {file = "pandas-2.1.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e7f12b2de0060b0b858cfec0016e7d980ae5bae455a1746bfcc70929100ee633"}, - {file = "pandas-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:83c166b9bb27c1715bed94495d9598a7f02950b4749dba9349c1dd2cbf10729d"}, - {file = "pandas-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:25c9976c17311388fcd953cb3d0697999b2205333f4e11e669d90ff8d830d429"}, - {file = "pandas-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:851b5afbb0d62f6129ae891b533aa508cc357d5892c240c91933d945fff15731"}, - {file = "pandas-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:e78507adcc730533619de07bfdd1c62b2918a68cd4419ea386e28abf7f6a1e5c"}, - {file = "pandas-2.1.2.tar.gz", hash = "sha256:52897edc2774d2779fbeb6880d2cfb305daa0b1a29c16b91f531a18918a6e0f3"}, + {file = "pandas-2.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e4c7c9f27a4185304c7caf96dc7d91bc60bc162221152de697c98eb0b2648dd8"}, + {file = "pandas-2.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f167beed68918d62bffb6ec64f2e1d8a7d297a038f86d4aed056b9493fca407f"}, + {file = "pandas-2.0.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ce0c6f76a0f1ba361551f3e6dceaff06bde7514a374aa43e33b588ec10420183"}, + {file = "pandas-2.0.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba619e410a21d8c387a1ea6e8a0e49bb42216474436245718d7f2e88a2f8d7c0"}, + {file = "pandas-2.0.3-cp310-cp310-win32.whl", hash = "sha256:3ef285093b4fe5058eefd756100a367f27029913760773c8bf1d2d8bebe5d210"}, + {file = "pandas-2.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:9ee1a69328d5c36c98d8e74db06f4ad518a1840e8ccb94a4ba86920986bb617e"}, + {file = "pandas-2.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b084b91d8d66ab19f5bb3256cbd5ea661848338301940e17f4492b2ce0801fe8"}, + {file = "pandas-2.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37673e3bdf1551b95bf5d4ce372b37770f9529743d2498032439371fc7b7eb26"}, + {file = "pandas-2.0.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9cb1e14fdb546396b7e1b923ffaeeac24e4cedd14266c3497216dd4448e4f2d"}, + {file = "pandas-2.0.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d9cd88488cceb7635aebb84809d087468eb33551097d600c6dad13602029c2df"}, + {file = "pandas-2.0.3-cp311-cp311-win32.whl", hash = "sha256:694888a81198786f0e164ee3a581df7d505024fbb1f15202fc7db88a71d84ebd"}, + {file = "pandas-2.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:6a21ab5c89dcbd57f78d0ae16630b090eec626360085a4148693def5452d8a6b"}, + {file = "pandas-2.0.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9e4da0d45e7f34c069fe4d522359df7d23badf83abc1d1cef398895822d11061"}, + {file = "pandas-2.0.3-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:32fca2ee1b0d93dd71d979726b12b61faa06aeb93cf77468776287f41ff8fdc5"}, + {file = "pandas-2.0.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:258d3624b3ae734490e4d63c430256e716f488c4fcb7c8e9bde2d3aa46c29089"}, + {file = "pandas-2.0.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9eae3dc34fa1aa7772dd3fc60270d13ced7346fcbcfee017d3132ec625e23bb0"}, + {file = "pandas-2.0.3-cp38-cp38-win32.whl", hash = "sha256:f3421a7afb1a43f7e38e82e844e2bca9a6d793d66c1a7f9f0ff39a795bbc5e02"}, + {file = "pandas-2.0.3-cp38-cp38-win_amd64.whl", hash = "sha256:69d7f3884c95da3a31ef82b7618af5710dba95bb885ffab339aad925c3e8ce78"}, + {file = "pandas-2.0.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:5247fb1ba347c1261cbbf0fcfba4a3121fbb4029d95d9ef4dc45406620b25c8b"}, + {file = "pandas-2.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:81af086f4543c9d8bb128328b5d32e9986e0c84d3ee673a2ac6fb57fd14f755e"}, + {file = "pandas-2.0.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1994c789bf12a7c5098277fb43836ce090f1073858c10f9220998ac74f37c69b"}, + {file = "pandas-2.0.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ec591c48e29226bcbb316e0c1e9423622bc7a4eaf1ef7c3c9fa1a3981f89641"}, + {file = "pandas-2.0.3-cp39-cp39-win32.whl", hash = "sha256:04dbdbaf2e4d46ca8da896e1805bc04eb85caa9a82e259e8eed00254d5e0c682"}, + {file = "pandas-2.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:1168574b036cd8b93abc746171c9b4f1b83467438a5e45909fed645cf8692dbc"}, + {file = "pandas-2.0.3.tar.gz", hash = "sha256:c02f372a88e0d17f36d3093a644c73cfc1788e876a7c4bcb4020a77512e2043c"}, ] [package.dependencies] numpy = [ - {version = ">=1.22.4,<2", markers = "python_version < \"3.11\""}, - {version = ">=1.23.2,<2", markers = "python_version == \"3.11\""}, - {version = ">=1.26.0,<2", markers = "python_version >= \"3.12\""}, + {version = ">=1.20.3", markers = "python_version < \"3.10\""}, + {version = ">=1.23.2", markers = "python_version >= \"3.11\""}, + {version = ">=1.21.0", markers = "python_version >= \"3.10\" and python_version < \"3.11\""}, ] python-dateutil = ">=2.8.2" pytz = ">=2020.1" tzdata = ">=2022.1" [package.extras] -all = ["PyQt5 (>=5.15.6)", "SQLAlchemy (>=1.4.36)", "beautifulsoup4 (>=4.11.1)", "bottleneck (>=1.3.4)", "dataframe-api-compat (>=0.1.7)", "fastparquet (>=0.8.1)", "fsspec (>=2022.05.0)", "gcsfs (>=2022.05.0)", "html5lib (>=1.1)", "hypothesis (>=6.46.1)", "jinja2 (>=3.1.2)", "lxml (>=4.8.0)", "matplotlib (>=3.6.1)", "numba (>=0.55.2)", "numexpr (>=2.8.0)", "odfpy (>=1.4.1)", "openpyxl (>=3.0.10)", "pandas-gbq (>=0.17.5)", "psycopg2 (>=2.9.3)", "pyarrow (>=7.0.0)", "pymysql (>=1.0.2)", "pyreadstat (>=1.1.5)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)", "pyxlsb (>=1.0.9)", "qtpy (>=2.2.0)", "s3fs (>=2022.05.0)", "scipy (>=1.8.1)", "tables (>=3.7.0)", "tabulate (>=0.8.10)", "xarray (>=2022.03.0)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.3)", "zstandard (>=0.17.0)"] -aws = ["s3fs (>=2022.05.0)"] -clipboard = ["PyQt5 (>=5.15.6)", "qtpy (>=2.2.0)"] -compression = ["zstandard (>=0.17.0)"] -computation = ["scipy (>=1.8.1)", "xarray (>=2022.03.0)"] -consortium-standard = ["dataframe-api-compat (>=0.1.7)"] -excel = ["odfpy (>=1.4.1)", "openpyxl (>=3.0.10)", "pyxlsb (>=1.0.9)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.3)"] +all = ["PyQt5 (>=5.15.1)", "SQLAlchemy (>=1.4.16)", "beautifulsoup4 (>=4.9.3)", "bottleneck (>=1.3.2)", "brotlipy (>=0.7.0)", "fastparquet (>=0.6.3)", "fsspec (>=2021.07.0)", "gcsfs (>=2021.07.0)", "html5lib (>=1.1)", "hypothesis (>=6.34.2)", "jinja2 (>=3.0.0)", "lxml (>=4.6.3)", "matplotlib (>=3.6.1)", "numba (>=0.53.1)", "numexpr (>=2.7.3)", "odfpy (>=1.4.1)", "openpyxl (>=3.0.7)", "pandas-gbq (>=0.15.0)", "psycopg2 (>=2.8.6)", "pyarrow (>=7.0.0)", "pymysql (>=1.0.2)", "pyreadstat (>=1.1.2)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)", "python-snappy (>=0.6.0)", "pyxlsb (>=1.0.8)", "qtpy (>=2.2.0)", "s3fs (>=2021.08.0)", "scipy (>=1.7.1)", "tables (>=3.6.1)", "tabulate (>=0.8.9)", "xarray (>=0.21.0)", "xlrd (>=2.0.1)", "xlsxwriter (>=1.4.3)", "zstandard (>=0.15.2)"] +aws = ["s3fs (>=2021.08.0)"] +clipboard = ["PyQt5 (>=5.15.1)", "qtpy (>=2.2.0)"] +compression = ["brotlipy (>=0.7.0)", "python-snappy (>=0.6.0)", "zstandard (>=0.15.2)"] +computation = ["scipy (>=1.7.1)", "xarray (>=0.21.0)"] +excel = ["odfpy (>=1.4.1)", "openpyxl (>=3.0.7)", "pyxlsb (>=1.0.8)", "xlrd (>=2.0.1)", "xlsxwriter (>=1.4.3)"] feather = ["pyarrow (>=7.0.0)"] -fss = ["fsspec (>=2022.05.0)"] -gcp = ["gcsfs (>=2022.05.0)", "pandas-gbq (>=0.17.5)"] -hdf5 = ["tables (>=3.7.0)"] -html = ["beautifulsoup4 (>=4.11.1)", "html5lib (>=1.1)", "lxml (>=4.8.0)"] -mysql = ["SQLAlchemy (>=1.4.36)", "pymysql (>=1.0.2)"] -output-formatting = ["jinja2 (>=3.1.2)", "tabulate (>=0.8.10)"] +fss = ["fsspec (>=2021.07.0)"] +gcp = ["gcsfs (>=2021.07.0)", "pandas-gbq (>=0.15.0)"] +hdf5 = ["tables (>=3.6.1)"] +html = ["beautifulsoup4 (>=4.9.3)", "html5lib (>=1.1)", "lxml (>=4.6.3)"] +mysql = ["SQLAlchemy (>=1.4.16)", "pymysql (>=1.0.2)"] +output-formatting = ["jinja2 (>=3.0.0)", "tabulate (>=0.8.9)"] parquet = ["pyarrow (>=7.0.0)"] -performance = ["bottleneck (>=1.3.4)", "numba (>=0.55.2)", "numexpr (>=2.8.0)"] +performance = ["bottleneck (>=1.3.2)", "numba (>=0.53.1)", "numexpr (>=2.7.1)"] plot = ["matplotlib (>=3.6.1)"] -postgresql = ["SQLAlchemy (>=1.4.36)", "psycopg2 (>=2.9.3)"] -spss = ["pyreadstat (>=1.1.5)"] -sql-other = ["SQLAlchemy (>=1.4.36)"] -test = ["hypothesis (>=6.46.1)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)"] -xml = ["lxml (>=4.8.0)"] +postgresql = ["SQLAlchemy (>=1.4.16)", "psycopg2 (>=2.8.6)"] +spss = ["pyreadstat (>=1.1.2)"] +sql-other = ["SQLAlchemy (>=1.4.16)"] +test = ["hypothesis (>=6.34.2)", "pytest (>=7.3.2)", "pytest-asyncio (>=0.17.0)", "pytest-xdist (>=2.2.0)"] +xml = ["lxml (>=4.6.3)"] [[package]] name = "pandas-stubs" -version = "2.1.1.230928" +version = "1.5.3.230321" +description = "Type annotations for pandas" +optional = false +python-versions = ">=3.8,<3.12" +files = [ + {file = "pandas_stubs-1.5.3.230321-py3-none-any.whl", hash = "sha256:4bf36b3071dd55f0e558ac8efe07676a120f2ed89e7a3df0fb78ddf2733bf247"}, + {file = "pandas_stubs-1.5.3.230321.tar.gz", hash = "sha256:2fa860df9e6058e9f0d2c09bc711c09abb8f0516eee7f0b9f9950d29b835fc6f"}, +] + +[package.dependencies] +types-pytz = ">=2022.1.1" + +[[package]] +name = "pandas-stubs" +version = "2.1.4.231227" description = "Type annotations for pandas" optional = false python-versions = ">=3.9" files = [ - {file = "pandas_stubs-2.1.1.230928-py3-none-any.whl", hash = "sha256:992d97159e054ca3175ebe8321ac5616cf6502dd8218b03bb0eaf3c4f6939037"}, - {file = "pandas_stubs-2.1.1.230928.tar.gz", hash = "sha256:ce1691c71c5d67b8f332da87763f7f54650f46895d99964d588c3a5d79e2cacc"}, + {file = "pandas_stubs-2.1.4.231227-py3-none-any.whl", hash = "sha256:211fc23e6ae87073bdf41dbf362c4a4d85e1e3477cb078dbac3da6c7fdaefba8"}, + {file = "pandas_stubs-2.1.4.231227.tar.gz", hash = "sha256:3ea29ef001e9e44985f5ebde02d4413f94891ef6ec7e5056fb07d125be796c23"}, ] [package.dependencies] @@ -689,6 +758,7 @@ files = [ ] [package.dependencies] +astunparse = {version = "*", markers = "python_version < \"3.9\""} Jinja2 = ">=2.11.0" MarkupSafe = "*" pygments = ">=2.12.0" @@ -1033,20 +1103,6 @@ files = [ {file = "types_pytz-2023.3.1.1-py3-none-any.whl", hash = "sha256:1999a123a3dc0e39a2ef6d19f3f8584211de9e6a77fe7a0259f04a524e90a5cf"}, ] -[[package]] -name = "types-requests" -version = "2.31.0.10" -description = "Typing stubs for requests" -optional = false -python-versions = ">=3.7" -files = [ - {file = "types-requests-2.31.0.10.tar.gz", hash = "sha256:dc5852a76f1eaf60eafa81a2e50aefa3d1f015c34cf0cba130930866b1b22a92"}, - {file = "types_requests-2.31.0.10-py3-none-any.whl", hash = "sha256:b32b9a86beffa876c0c3ac99a4cd3b8b51e973fb8e3bd4e0a6bb32c7efad80fc"}, -] - -[package.dependencies] -urllib3 = ">=2" - [[package]] name = "types-tqdm" version = "4.66.0.4" @@ -1122,10 +1178,24 @@ files = [ [package.extras] tests = ["flake8", "pytest", "pytest-cov", "requests"] +[[package]] +name = "wheel" +version = "0.42.0" +description = "A built-package format for Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "wheel-0.42.0-py3-none-any.whl", hash = "sha256:177f9c9b0d45c47873b619f5b650346d632cdc35fb5e4d25058e09c9e581433d"}, + {file = "wheel-0.42.0.tar.gz", hash = "sha256:c45be39f7882c9d34243236f2d63cbd58039e360f85d0913425fbd7ceea617a8"}, +] + +[package.extras] +test = ["pytest (>=6.0.0)", "setuptools (>=65)"] + [extras] grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio", "lz4", "protobuf"] [metadata] lock-version = "2.0" -python-versions = ">=3.9,<3.13" -content-hash = "fa552381e2fb77005a53c49211b836d403c6796ebc1f4e7b614852cc5712c1e7" +python-versions = ">=3.8,<3.13" +content-hash = "e9c4475c8166329908aba5405167a0c79c0c108634b0b15a0ec37231c997e705" diff --git a/pyproject.toml b/pyproject.toml index e1dce11fe..a684277b2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,18 +3,11 @@ line-length = 120 target-version = ['py38'] include = '\.pyi?$' exclude = ''' - ( /( - \.eggs # exclude a few common directories in the - | \.git # root of the project - | \.hg - | \.mypy_cache - | \.venv - | _build - | buck-out - | build - | dist + \.git # exclude a few common directories in the + | \.mypy_cache # root of the project + | \.pytest_cache )/ | foo.py # also separately exclude a file named foo.py in # the root of the project @@ -54,11 +47,9 @@ classifiers=[ ] [tool.poetry.dependencies] -python = ">=3.9,<3.13" -requests = "^2.31.0" +python = ">=3.8,<3.13" typing-extensions = ">=3.7.4" -python-dateutil = ">=2.5.3" -urllib3 = "2.0.7" +urllib3 = ">=1.26.16" tqdm = ">=4.64.1" grpcio = { version = ">=1.44.0", optional = true } grpc-gateway-protoc-gen-openapiv2 = { version = "0.1.0", optional = true } @@ -66,8 +57,26 @@ googleapis-common-protos = { version = ">=1.53.0", optional = true } lz4 = { version = ">=3.1.3", optional = true } protobuf = { version = "~=3.20.0", optional = true } +[tool.poetry.group.types] +optional = true + +[tool.poetry.group.types.dependencies] +mypy = "^1.6.1" +types-urllib3 = "^1.26.25.14" +grpc-stubs = "^1.53.0.3" +pandas-stubs = [ + {version = "^2.1.1.230928", python = ">=3.9"}, + {version = "^1.5.3.230321", python = ">=3.8,<3.9"} +] +types-tqdm = "^4.66.0.3" +types-protobuf = "^4.24.0.4" + [tool.poetry.group.dev.dependencies] -numpy = ">=1.22" +numpy = [ + { version = ">=1.22", python = ">=3.9" }, + { version = ">=1.21", python = ">=3.8,<3.9" }, +] +pandas = ">=1.3.5" pdoc = "^14.1.0" pytest = "7.2.0" pytest-asyncio = "0.15.1" @@ -76,14 +85,6 @@ pytest-mock = "3.6.1" pytest-timeout = "1.4.2" urllib3_mock = "0.3.3" responses = ">=0.8.1" -pandas = ">=1.3.5" -mypy = "^1.6.1" -types-requests = "^2.31.0.10" -types-urllib3 = "^1.26.25.14" -grpc-stubs = "^1.53.0.3" -pandas-stubs = "^2.1.1.230928" -types-tqdm = "^4.66.0.3" -types-protobuf = "^4.24.0.4" [tool.poetry.extras] grpc = ["grpcio", "grpc-gateway-protoc-gen-openapiv2", "googleapis-common-protos", "lz4", "protobuf"] diff --git a/scripts/create.py b/scripts/create.py new file mode 100644 index 000000000..352c2137e --- /dev/null +++ b/scripts/create.py @@ -0,0 +1,37 @@ +import os +import random +import string +from pinecone import Pinecone + +def read_env_var(name): + value = os.environ.get(name) + if value is None: + raise 'Environment variable {} is not set'.format(name) + return value + +def random_string(length): + return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) + +def write_gh_output(name, value): + with open(os.environ['GITHUB_OUTPUT'], 'a') as fh: + print(f'{name}={value}', file=fh) + +def main(): + pc = Pinecone(api_key=read_env_var('PINECONE_API_KEY')) + index_name = read_env_var('NAME_PREFIX') + random_string(20) + pc.create_index( + name=index_name, + metric=read_env_var('METRIC'), + dimension=int(read_env_var('DIMENSION')), + spec={ + 'serverless': { + 'cloud': read_env_var('CLOUD'), + 'region': read_env_var('REGION'), + } + } + ) + write_gh_output('index_name', index_name) + +if __name__ == '__main__': + main() + diff --git a/scripts/delete.py b/scripts/delete.py new file mode 100644 index 000000000..af047fea9 --- /dev/null +++ b/scripts/delete.py @@ -0,0 +1,17 @@ +import os +from pinecone import Pinecone + +def read_env_var(name): + value = os.environ.get(name) + if value is None: + raise 'Environment variable {} is not set'.format(name) + return value + +def main(): + pc = Pinecone(api_key=read_env_var('PINECONE_API_KEY')) + to_delete = read_env_var('INDEX_NAME') + pc.delete_index(name=to_delete) + print('Index deleted: ' + to_delete) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/tests/dependency/grpc/test_sanity.py b/tests/dependency/grpc/test_sanity.py new file mode 100644 index 000000000..c278b607d --- /dev/null +++ b/tests/dependency/grpc/test_sanity.py @@ -0,0 +1,45 @@ +import pytest +import os +import time +from pinecone.grpc import PineconeGRPC + +@pytest.fixture +def index_name(): + name = os.environ.get('INDEX_NAME', None) + if name is None: + raise 'INDEX_NAME environment variable is not set' + return name + +@pytest.fixture +def client(): + return PineconeGRPC(api_key=os.environ.get('PINECONE_API_KEY')) + +class TestSanityRest: + def test_sanity(self, index_name, client): + print('Testing with index name: ' + index_name) + assert index_name != '' + + # Verify index exists with expected properties + assert index_name in client.list_indexes().names() + description = client.describe_index(name=index_name) + assert description.dimension == 2 + + idx = client.Index(index_name) + idx.upsert(vectors=[ + ('1', [1.0, 2.0]), + ('2', [3.0, 4.0]), + ('3', [5.0, 6.0]) + ]) + + # Wait for index freshness + time.sleep(30) + + # Check the vector count reflects some data has been upserted + description = idx.describe_index_stats() + assert description.dimension == 2 + assert description.total_vector_count == 3 + + # Query for results + query_results = idx.query(id='1', top_k=10, include_values=True) + assert query_results.matches[0].id == '1' + assert len(query_results.matches) == 3 \ No newline at end of file diff --git a/tests/dependency/rest/test_sanity.py b/tests/dependency/rest/test_sanity.py new file mode 100644 index 000000000..7e348b103 --- /dev/null +++ b/tests/dependency/rest/test_sanity.py @@ -0,0 +1,45 @@ +import pytest +import os +import time +from pinecone import Pinecone + +@pytest.fixture +def index_name(): + name = os.environ.get('INDEX_NAME', None) + if name is None or name == '': + raise 'INDEX_NAME environment variable is not set' + return name + +@pytest.fixture +def client(): + return Pinecone(api_key=os.environ.get('PINECONE_API_KEY')) + +class TestSanityRest: + def test_sanity(self, index_name, client): + print('Testing with index name: ' + index_name) + assert index_name != '' + + # Verify index exists with expected properties + assert index_name in client.list_indexes().names() + description = client.describe_index(name=index_name) + assert description.dimension == 2 + + idx = client.Index(index_name) + idx.upsert(vectors=[ + ('1', [1.0, 2.0]), + ('2', [3.0, 4.0]), + ('3', [5.0, 6.0]) + ]) + + # Wait for index freshness + time.sleep(30) + + # Check the vector count reflects some data has been upserted + description = idx.describe_index_stats() + assert description.dimension == 2 + assert description.total_vector_count == 3 + + # Query for results + query_results = idx.query(id='1', top_k=10, include_values=True) + assert query_results.matches[0].id == '1' + assert len(query_results.matches) == 3 \ No newline at end of file diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 4e8f3b9ab..0abe1296f 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,3 +1,4 @@ +import os import pytest import random import time @@ -108,7 +109,9 @@ def cleanup_all(): client = Pinecone() for index in client.list_indexes(): - try: - delete_with_retry(client, index.name) - except: - pass \ No newline at end of file + buildNumber = os.getenv('GITHUB_BUILD_NUMBER') + if index.name.startswith(buildNumber): + try: + delete_with_retry(client, index.name) + except: + pass \ No newline at end of file diff --git a/tests/unit/utils/test_user_agent.py b/tests/unit/utils/test_user_agent.py index 09525d9a7..38272be45 100644 --- a/tests/unit/utils/test_user_agent.py +++ b/tests/unit/utils/test_user_agent.py @@ -5,5 +5,4 @@ class TestUserAgent(): def test_user_agent(self): useragent = get_user_agent() assert re.search(r"python-client-\d+\.\d+\.\d+", useragent) is not None - assert re.search(r"requests:\d+\.\d+\.\d+", useragent) is not None assert re.search(r"urllib3:\d+\.\d+\.\d+", useragent) is not None \ No newline at end of file From 65343d5d81cb6faefdb26b9de0245ea0a1bb820b Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 9 Jan 2024 20:08:37 -0500 Subject: [PATCH 32/39] Update publish workflows with new testing setup (#266) ## Problem In #263 we split our tests across two different workflows. We need to update our publishing workflows to find the test configurations in the new locations. ## Solution Replace references to `testing.yaml` with references to `testing-grpc.yaml` and `testing-rest.yaml`. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) --- .github/workflows/alpha-release.yaml | 11 ++++++++--- .github/workflows/nightly-release.yaml | 11 ++++++++--- .github/workflows/release.yaml | 11 ++++++++--- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/.github/workflows/alpha-release.yaml b/.github/workflows/alpha-release.yaml index aeac3e294..fb71db914 100644 --- a/.github/workflows/alpha-release.yaml +++ b/.github/workflows/alpha-release.yaml @@ -24,13 +24,18 @@ on: default: 'rc1' jobs: - testing: - uses: './.github/workflows/testing.yaml' + testing-rest: + uses: './.github/workflows/testing-rest.yaml' + secrets: inherit + testing-grpc: + uses: './.github/workflows/testing-grpc.yaml' secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' - needs: testing + needs: + - testing-rest + - testing-grpc with: isPrerelease: true ref: ${{ inputs.ref }} diff --git a/.github/workflows/nightly-release.yaml b/.github/workflows/nightly-release.yaml index 19b7daf75..6f26fb3d5 100644 --- a/.github/workflows/nightly-release.yaml +++ b/.github/workflows/nightly-release.yaml @@ -6,12 +6,17 @@ on: - cron: '0 0 * * *' jobs: - run-tests: - uses: './.github/workflows/testing.yaml' + testing-rest: + uses: './.github/workflows/testing-rest.yaml' + secrets: inherit + testing-grpc: + uses: './.github/workflows/testing-grpc.yaml' secrets: inherit pypi-nightly: - needs: run-tests + needs: + - testing-rest + - testing-grpc timeout-minutes: 30 name: pypi-nightly runs-on: ubuntu-latest diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 3377ca565..fe38cbe24 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,13 +19,18 @@ on: - 'major' # breaking changes jobs: - testing: - uses: './.github/workflows/testing.yaml' + testing-rest: + uses: './.github/workflows/testing-rest.yaml' + secrets: inherit + testing-grpc: + uses: './.github/workflows/testing-grpc.yaml' secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' - needs: testing + needs: + - testing-rest + - testing-grpc with: isPrerelease: false ref: ${{ inputs.ref }} From 1dd381e8e5e50220ac55cd10db073e8b6bc937b5 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Tue, 9 Jan 2024 21:07:34 -0500 Subject: [PATCH 33/39] Expand urllib3 compatibility to 1.26.0 (#267) ## Problem In #263 we tested urllib3 compatibility back to 1.26.16. I can't recall where that specific number came from, but I want to try going all the way back to 1.26.0 (a 2020 release) and see if that causes any issues. The [urllib3 migration guide](https://urllib3.readthedocs.io/en/stable/v2-migration-guide.html#migrating-as-a-package-maintainer) suggests keeping support at 1.26.x so I'm hopeful things will just work since they seem pretty sensitive to the needs of maintainers. ## Solution Adjust test matrix and `pyproject.toml`. ## Type of Change - [x] New feature (non-breaking change which adds functionality) --- .github/workflows/testing-rest.yaml | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/testing-rest.yaml b/.github/workflows/testing-rest.yaml index 31e9dadfb..298dc2dfe 100644 --- a/.github/workflows/testing-rest.yaml +++ b/.github/workflows/testing-rest.yaml @@ -117,7 +117,7 @@ jobs: # - 3.12 # - 3.13 urllib3-version: - - 1.26.16 + - 1.26.0 - 1.26.18 - 2.0.2 - 2.0.5 diff --git a/pyproject.toml b/pyproject.toml index a684277b2..d78660adb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ classifiers=[ [tool.poetry.dependencies] python = ">=3.8,<3.13" typing-extensions = ">=3.7.4" -urllib3 = ">=1.26.16" +urllib3 = ">=1.26.0" tqdm = ">=4.64.1" grpcio = { version = ">=1.44.0", optional = true } grpc-gateway-protoc-gen-openapiv2 = { version = "0.1.0", optional = true } From 93a04caf359f47955a332e7ab0483b981b6f288a Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 12 Jan 2024 15:26:02 -0500 Subject: [PATCH 34/39] Data plane integration testing suite (#268) ## Problem Want to add a much more comprehensive integration testing suite against the data plane. This is a large undertaking because of the amount of variables involved, but this is a start. Some variables to consider: - REST vs GRPC - pod vs serverless - environment/cloud/region - freshness timeout - index metric, since hybrid search only makes sense for dotproduct ## Solution Conceptually, I want every test run on github actions to target one combination of the factors above. This means some things which might otherwise be handled through test parameterization in a big monolithic test suite that is run with a single command are now toggled through environment variables. This makes it very easy to setup parallel runs with different configurations, but at the cost of some additional complexity. There's currently no single command to run every combo from my local machine in one go. To run these locally right now, I might have an incantation like this: ```shell PINECONE_API_KEY='nana-nana-nana-nana-batman' \ METRIC='cosine' \ USE_GRPC='false' \ SPEC='{"serverless": {"region": "us-west-2", "cloud": "aws"}}' \ poetry run pytest tests/integration/data/ -s -vv ``` - In CI, I shove this ugliness into a reusable github action `test-data-plane` that allow tests to easily be run using different configurations for target environment/cloud/region, REST vs GRPC, and metric type (which is relevant because hybrid search / sparse vector stuff only makes sense in the context of indexes with metric=dotproduct). - Since waiting on data freshness is another bottleneck in the execution, I try to seed some data upfront and use it for all my query/fetch testing. - By using the exact same tests via GRPC and REST for the first time, I'm discovering a lot of small details that don't match. So I'm making adjustments as I go to bring them into alignment, at least on the happy path. Error handling is a complex beast and will need more iteration in the future. - Migrated some logic from IndexGRPC in to another vector factory class to allow `IndexGRPC#upsert` to accept `Vector` or `VectorGRPC` args. This greatly simplifies test reuse and will be a nice UX improvement for users also because it simplifies docs. - Refactored a bit in the GRPC "unit" tests which were and still are a disaster. I found myself crawling through those after refactoring the `IndexGRPC` class to use the new `VectoryFactoryGRPC` class and triggering a few failures due to missed a few edge cases expressed through the unit tests. I split things up into smaller files and transitioned from using `self.` everywhere to using pytest fixtures instead. It still sucks, but readability maybe slightly improved. - An example of something that changed (for alignment reasons) is that in the past an empty fetch result would be `None` via GRPC or `FetchResult(vectors=[])` via REST. The simplicity of `None` was nice, but now that there is `read_unit` information to display even when there are no results, the `FetchResponse` return value makes more sense. - Implemented a vector factory for GRPC that is very similar to the one I created a while ago for the REST code path. It's much much easier to test edge cases in that class alone than in a more integrationy unit test that requires me to mock/patch a bunch of stuff that would otherwise fire off network calls. To save resources/time while initially building out these tests, for now I'm only running with serverless indexes. But it should be easy to add other configurations soon. ## Some possible bugs/questions to follow up: - Seems like `$ne` and `$nin` aren't working [as documented](https://docs.pinecone.io/docs/metadata-filtering) - Freshness seems much different on dotproduct indexes. Not sure if this is expected. - Need to rename `readUnits` to `read_units` before shipping 3.0 ## High-level coverage so far - [x] Upsert - [x] Upsert (sparse vec) - [x] Fetch - [x] Query - [x] Query (metadata filters) - [ ] Query (hybrid / sparse vec) - [ ] Update - [ ] DescribeIndexStats - [ ] Delete ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [x] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] This change requires a documentation update - [x] Infrastructure change (CI configs, etc) - [x] Non-code change (docs, etc) --- .github/actions/test-data-plane/action.yaml | 57 ++ .github/workflows/alpha-release.yaml | 16 +- .github/workflows/nightly-release.yaml | 16 +- .github/workflows/pr.yaml | 13 +- .github/workflows/release.yaml | 16 +- ...ting-grpc.yaml => testing-dependency.yaml} | 88 ++- .github/workflows/testing-integration.yaml | 91 +++ .github/workflows/testing-rest.yaml | 155 ---- .github/workflows/testing-unit.yaml | 37 + pinecone/__init__.py | 5 +- pinecone/control/__init__.py | 1 + pinecone/data/__init__.py | 11 +- pinecone/data/index.py | 2 +- pinecone/data/vector_factory.py | 13 +- pinecone/grpc/__init__.py | 11 +- pinecone/grpc/index_grpc.py | 77 +- pinecone/grpc/utils.py | 22 +- pinecone/grpc/vector_factory_grpc.py | 122 +++ pinecone/utils/convert_to_list.py | 2 +- poetry.lock | 2 +- tests/integration/control/__init__.py | 0 tests/integration/{ => control}/conftest.py | 2 +- .../{ => control}/test_collections.py | 0 .../test_create_index_api_errors.py | 0 .../test_create_index_sl_happy_path.py | 0 .../test_create_index_timeouts.py | 0 .../test_create_index_type_errors.py | 0 .../{ => control}/test_describe_index.py | 0 .../{ => control}/test_list_indexes.py | 0 tests/integration/data/__init__.py | 0 tests/integration/data/conftest.py | 83 +++ tests/integration/data/seed.py | 34 + tests/integration/data/test_fetch.py | 79 ++ tests/integration/data/test_query.py | 189 +++++ tests/integration/data/test_query_errors.py | 33 + tests/integration/data/test_upsert.py | 86 +++ tests/integration/data/test_upsert_errors.py | 187 +++++ tests/integration/data/utils.py | 5 + tests/integration/helpers/__init__.py | 8 + tests/integration/helpers/helpers.py | 39 + tests/unit/utils/test_convert_to_list.py | 1 + tests/unit_grpc/conftest.py | 55 ++ tests/unit_grpc/test_grpc_index.py | 694 ------------------ .../test_grpc_index_describe_index_stats.py | 37 + tests/unit_grpc/test_grpc_index_fetch.py | 35 + tests/unit_grpc/test_grpc_index_query.py | 72 ++ tests/unit_grpc/test_grpc_index_update.py | 45 ++ tests/unit_grpc/test_grpc_index_upsert.py | 580 +++++++++++++++ tests/unit_grpc/test_vector_factory_grpc.py | 294 ++++++++ 49 files changed, 2312 insertions(+), 1003 deletions(-) create mode 100644 .github/actions/test-data-plane/action.yaml rename .github/workflows/{testing-grpc.yaml => testing-dependency.yaml} (68%) create mode 100644 .github/workflows/testing-integration.yaml delete mode 100644 .github/workflows/testing-rest.yaml create mode 100644 .github/workflows/testing-unit.yaml create mode 100644 pinecone/control/__init__.py create mode 100644 pinecone/grpc/vector_factory_grpc.py create mode 100644 tests/integration/control/__init__.py rename tests/integration/{ => control}/conftest.py (98%) rename tests/integration/{ => control}/test_collections.py (100%) rename tests/integration/{ => control}/test_create_index_api_errors.py (100%) rename tests/integration/{ => control}/test_create_index_sl_happy_path.py (100%) rename tests/integration/{ => control}/test_create_index_timeouts.py (100%) rename tests/integration/{ => control}/test_create_index_type_errors.py (100%) rename tests/integration/{ => control}/test_describe_index.py (100%) rename tests/integration/{ => control}/test_list_indexes.py (100%) create mode 100644 tests/integration/data/__init__.py create mode 100644 tests/integration/data/conftest.py create mode 100644 tests/integration/data/seed.py create mode 100644 tests/integration/data/test_fetch.py create mode 100644 tests/integration/data/test_query.py create mode 100644 tests/integration/data/test_query_errors.py create mode 100644 tests/integration/data/test_upsert.py create mode 100644 tests/integration/data/test_upsert_errors.py create mode 100644 tests/integration/data/utils.py create mode 100644 tests/unit_grpc/conftest.py delete mode 100644 tests/unit_grpc/test_grpc_index.py create mode 100644 tests/unit_grpc/test_grpc_index_describe_index_stats.py create mode 100644 tests/unit_grpc/test_grpc_index_fetch.py create mode 100644 tests/unit_grpc/test_grpc_index_query.py create mode 100644 tests/unit_grpc/test_grpc_index_update.py create mode 100644 tests/unit_grpc/test_grpc_index_upsert.py create mode 100644 tests/unit_grpc/test_vector_factory_grpc.py diff --git a/.github/actions/test-data-plane/action.yaml b/.github/actions/test-data-plane/action.yaml new file mode 100644 index 000000000..e04ed8749 --- /dev/null +++ b/.github/actions/test-data-plane/action.yaml @@ -0,0 +1,57 @@ +name: 'Test Data Plane' +description: 'Runs tests on the Pinecone data plane' + +# - pod vs serverless +# - grpc vs rest +# - metric -> vector vs sparse vector +# - namespace: default vs custom +# - environment: free vs paid +# - with metadata vs without metadata + +inputs: + metric: + description: 'The metric of the index' + required: true + spec: + description: 'The deploy spec of the index' + required: true + use_grpc: + description: 'Whether to use gRPC or REST' + required: true + freshness_timeout_seconds: + description: 'The number of seconds to wait for the index to become fresh' + required: false + default: '60' + PINECONE_API_KEY: + description: 'The Pinecone API key' + required: true + +outputs: + index_name: + description: 'The name of the index, including randomized suffix' + value: ${{ steps.create-index.outputs.index_name }} + +runs: + using: 'composite' + steps: + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: ${{ inputs.use_grpc }} + include_dev: 'true' + + - name: Run data plane tests + id: data-plane-tests + shell: bash + run: poetry run pytest tests/integration/data + env: + PINECONE_API_KEY: ${{ inputs.PINECONE_API_KEY }} + USE_GRPC: ${{ inputs.use_grpc }} + METRIC: ${{ inputs.metric }} + SPEC: ${{ inputs.spec }} + FRESHNESS_TIMEOUT_SECONDS: ${{ inputs.freshness_timeout_seconds }} \ No newline at end of file diff --git a/.github/workflows/alpha-release.yaml b/.github/workflows/alpha-release.yaml index fb71db914..dfb84929e 100644 --- a/.github/workflows/alpha-release.yaml +++ b/.github/workflows/alpha-release.yaml @@ -24,18 +24,22 @@ on: default: 'rc1' jobs: - testing-rest: - uses: './.github/workflows/testing-rest.yaml' + unit-tests: + uses: './.github/workflows/testing-unit.yaml' secrets: inherit - testing-grpc: - uses: './.github/workflows/testing-grpc.yaml' + 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: - - testing-rest - - testing-grpc + - unit-tests + - integration-tests + - dependency-tests with: isPrerelease: true ref: ${{ inputs.ref }} diff --git a/.github/workflows/nightly-release.yaml b/.github/workflows/nightly-release.yaml index 6f26fb3d5..eff556a8d 100644 --- a/.github/workflows/nightly-release.yaml +++ b/.github/workflows/nightly-release.yaml @@ -6,17 +6,21 @@ on: - cron: '0 0 * * *' jobs: - testing-rest: - uses: './.github/workflows/testing-rest.yaml' + unit-tests: + uses: './.github/workflows/testing-unit.yaml' secrets: inherit - testing-grpc: - uses: './.github/workflows/testing-grpc.yaml' + integration-tests: + uses: './.github/workflows/testing-integration.yaml' + secrets: inherit + dependency-tests: + uses: './.github/workflows/testing-dependency.yaml' secrets: inherit pypi-nightly: needs: - - testing-rest - - testing-grpc + - unit-tests + - integration-tests + - dependency-tests timeout-minutes: 30 name: pypi-nightly runs-on: ubuntu-latest diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index f48f7f5cb..8742622d5 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -8,11 +8,14 @@ on: workflow_dispatch: {} jobs: - run-tests-rest: - uses: './.github/workflows/testing-rest.yaml' + unit-tests: + uses: './.github/workflows/testing-unit.yaml' secrets: inherit - run-tests-grpc: - uses: './.github/workflows/testing-grpc.yaml' + integration-tests: + uses: './.github/workflows/testing-integration.yaml' + secrets: inherit + dependency-tests: + uses: './.github/workflows/testing-dependency.yaml' secrets: inherit package: name: Check packaging @@ -31,8 +34,6 @@ jobs: - name: Package run: poetry build - - build-docs: name: Build docs with pdoc runs-on: ubuntu-latest diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index fe38cbe24..c335b1b24 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,18 +19,22 @@ on: - 'major' # breaking changes jobs: - testing-rest: - uses: './.github/workflows/testing-rest.yaml' + unit-tests: + uses: './.github/workflows/testing-unit.yaml' secrets: inherit - testing-grpc: - uses: './.github/workflows/testing-grpc.yaml' + 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: - - testing-rest - - testing-grpc + - unit-tests + - integration-tests + - dependency-tests with: isPrerelease: false ref: ${{ inputs.ref }} diff --git a/.github/workflows/testing-grpc.yaml b/.github/workflows/testing-dependency.yaml similarity index 68% rename from .github/workflows/testing-grpc.yaml rename to .github/workflows/testing-dependency.yaml index 06ef24af5..05ccd7423 100644 --- a/.github/workflows/testing-grpc.yaml +++ b/.github/workflows/testing-dependency.yaml @@ -1,41 +1,11 @@ -name: Testing GRPC +name: Dependency Testing on: workflow_call: {} jobs: - units-grpc: - name: Unit tests (GRPC) - runs-on: ubuntu-latest - strategy: - matrix: - python-version: [3.8, 3.9, '3.10', 3.11] - - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - with: - include_grpc: true - - - name: Run unit tests (GRPC) - run: poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc - - - name: mypy check - run: | - # Still lots of errors when running on the whole package (especially - # in the generated core module), but we can check these subpackages - # so we don't add new regressions. - poetry run mypy pinecone --exclude pinecone/core - - dependency-matrix-grpc-setup: - name: Deps setup (GRPC) + dependency-matrix-setup: + name: Deps setup runs-on: ubuntu-latest outputs: index_name: ${{ steps.setup-index.outputs.index_name }} @@ -46,13 +16,13 @@ jobs: uses: ./.github/actions/create-index timeout-minutes: 5 with: - name_prefix: depstest-grpc-${{ github.run_number }} + name_prefix: depstest-${{ github.run_number }} dimension: 2 PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} dependency-matrix-grpc: name: Deps (GRPC) - needs: dependency-matrix-grpc-setup + needs: dependency-matrix-setup runs-on: ubuntu-latest strategy: max-parallel: 5 @@ -124,5 +94,49 @@ jobs: command: poetry run pytest tests/dependency/grpc -s -v env: PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - INDEX_NAME: ${{ needs.dependency-matrix-grpc-setup.outputs.index_name }} - \ No newline at end of file + INDEX_NAME: ${{ needs.dependency-matrix-setup.outputs.index_name }} + + + + + dependency-matrix-rest: + name: Deps (REST) + runs-on: ubuntu-latest + needs: dependency-matrix-setup + strategy: + max-parallel: 5 + fail-fast: false + matrix: + python-version: + - 3.8 + - 3.9 + - '3.10' + - 3.11 + urllib3-version: + - 1.26.0 + - 1.26.18 + - 2.0.2 + - 2.0.5 + - 2.1.0 + steps: + - uses: actions/checkout@v4 + - name: 'Set up Python ${{ matrix.python-version }}' + uses: actions/setup-python@v4 + with: + python-version: '${{ matrix.python-version }}' + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: false + include_types: false + - name: 'Install urllib3 ${{ matrix.urllib3-version }}' + run: 'poetry add urllib3==${{ matrix.urllib3-version }}' + - uses: nick-fields/retry@v2 + with: + timeout_minutes: 5 + max_attempts: 3 + retry_on: error + command: poetry run pytest tests/dependency/rest -s -v + env: + PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' + INDEX_NAME: '${{ needs.dependency-matrix-setup.outputs.index_name }}' diff --git a/.github/workflows/testing-integration.yaml b/.github/workflows/testing-integration.yaml new file mode 100644 index 000000000..e2b0631d3 --- /dev/null +++ b/.github/workflows/testing-integration.yaml @@ -0,0 +1,91 @@ +name: "Integration Tests" +'on': + workflow_call: {} + +jobs: + data-plane-serverless: + name: Data plane serverless integration tests + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + use_grpc: [true, false] + metric: + - cosine + # - euclidean + # - dotproduct + spec: + - '{ "serverless": { "region": "us-west-2", "cloud": "aws" }}' + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/test-data-plane + with: + use_grpc: '${{ matrix.use_grpc }}' + metric: '${{ matrix.metric }}' + spec: '${{ matrix.spec }}' + PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' + freshness_timeout_seconds: 600 + +# data-plane-pod: +# name: Data plane pod integration tests +# runs-on: ubuntu-latest +# strategy: +# max-parallel: 1 +# matrix: +# use_grpc: [true, false] +# metric: [cosine, dotproduct] +# spec: +# - '{ "pod": { "environment": "us-east1-gcp", "pod_type": "p1" }}' +# steps: +# - uses: actions/checkout@v4 +# - uses: ./.github/actions/test-data-plane +# with: +# use_grpc: '${{ matrix.use_grpc }}' +# metric: '${{ matrix.metric }}' +# spec: '${{ matrix.spec }}' +# PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' + + control-rest: + name: control plane + runs-on: ubuntu-latest + strategy: + matrix: + pineconeEnv: + - prod + testConfig: + - python-version: 3.8 # Do one test run with 3.8 for sanity check + pod: { environment: 'us-east1-gcp'} + serverless: { cloud: 'aws', region: 'us-west-2'} + - python-version: 3.11 + pod: { environment: 'us-east1-gcp'} + serverless: { cloud: 'aws', region: 'us-west-2'} + max-parallel: 1 + fail-fast: false + steps: + - uses: actions/checkout@v4 + - name: 'Set up Python ${{ matrix.testConfig.python-version }}' + uses: actions/setup-python@v4 + with: + python-version: '${{ matrix.testConfig.python-version }}' + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + - name: 'Run integration tests (REST, prod)' + if: matrix.pineconeEnv == 'prod' + run: poetry run pytest tests/integration/control -s -v + env: + PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' + PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' + GITHUB_BUILD_NUMBER: '${{ github.run_number }}-p-${{ matrix.testConfig.python-version}}' + POD_ENVIRONMENT: '${{ matrix.testConfig.pod.environment }}' + SERVERLESS_CLOUD: '${{ matrix.testConfig.serverless.cloud }}' + SERVERLESS_REGION: '${{ matrix.testConfig.serverless.region }}' + - name: 'Run integration tests (REST, staging)' + if: matrix.pineconeEnv == 'staging' + run: poetry run pytest tests/integration -s -v + env: + PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' + PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY_STAGING }}' + GITHUB_BUILD_NUMBER: '${{ github.run_number }}-s-${{ matrix.testConfig.python-version}}' + POD_ENVIRONMENT: '${{ matrix.testConfig.pod.environment }}' + SERVERLESS_CLOUD: '${{ matrix.testConfig.serverless.cloud }}' + SERVERLESS_REGION: '${{ matrix.testConfig.serverless.region }}' diff --git a/.github/workflows/testing-rest.yaml b/.github/workflows/testing-rest.yaml deleted file mode 100644 index 298dc2dfe..000000000 --- a/.github/workflows/testing-rest.yaml +++ /dev/null @@ -1,155 +0,0 @@ -name: Testing REST - -on: - workflow_call: {} - - -jobs: - units-rest: - name: Unit tests (REST) - runs-on: ubuntu-latest - strategy: - matrix: - python-version: [3.8, 3.9, '3.10', 3.11] - - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - - - name: Run unit tests - run: poetry run pytest --cov=pinecone --timeout=120 tests/unit - - - name: mypy check - run: | - # Still lots of errors when running on the whole package (especially - # in the generated core module), but we can check these subpackages - # so we don't add new regressions. - poetry run mypy pinecone --exclude pinecone/core --exclude pinecone/grpc - - integration-rest: - name: Integration tests (REST) - runs-on: ubuntu-latest - strategy: - matrix: - pineconeEnv: - - prod - # - staging - testConfig: - - python-version: 3.8 # Do one test run with 3.8 for sanity check - pod: { environment: 'us-east1-gcp'} - serverless: { cloud: 'aws', region: 'us-west-2'} - - python-version: 3.11 - pod: { environment: 'us-east1-gcp'} - serverless: { cloud: 'aws', region: 'us-west-2'} - max-parallel: 1 - fail-fast: false - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.testConfig.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.testConfig.python-version }} - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - - - name: Run integration tests (REST, prod) - if: matrix.pineconeEnv == 'prod' - run: poetry run pytest tests/integration -s -v - env: - PINECONE_CONTROLLER_HOST: 'https://api.pinecone.io' - PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - GITHUB_BUILD_NUMBER: "${{ github.run_number }}-p-${{ matrix.testConfig.python-version}}" - POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} - SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} - SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} - - - name: Run integration tests (REST, staging) - if: matrix.pineconeEnv == 'staging' - run: poetry run pytest tests/integration -s -v - env: - PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' - PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY_STAGING }} - GITHUB_BUILD_NUMBER: "${{ github.run_number }}-s-${{ matrix.testConfig.python-version}}" - POD_ENVIRONMENT: ${{ matrix.testConfig.pod.environment }} - SERVERLESS_CLOUD: ${{ matrix.testConfig.serverless.cloud }} - SERVERLESS_REGION: ${{ matrix.testConfig.serverless.region }} - - dependency-matrix-rest-setup: - name: Deps setup (REST) - runs-on: ubuntu-latest - outputs: - index_name: ${{ steps.setup-index-rest.outputs.index_name }} - steps: - - uses: actions/checkout@v4 - - name: Create index - id: setup-index-rest - uses: ./.github/actions/create-index - timeout-minutes: 5 - with: - name_prefix: depstest-rest-${{ github.run_number }} - dimension: 2 - PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - - - dependency-matrix-rest: - name: Deps (REST) - runs-on: ubuntu-latest - needs: dependency-matrix-rest-setup - strategy: - max-parallel: 5 - fail-fast: false - matrix: - python-version: - - 3.8 - - 3.9 - - "3.10" - - 3.11 - # Poetry doesn't yet work with 3.12 & 3.13 - # - 3.12 - # - 3.13 - urllib3-version: - - 1.26.0 - - 1.26.18 - - 2.0.2 - - 2.0.5 - - 2.1.0 - # - 1.26.17 - # - 2.0.3 - # - 2.0.4 - # - 2.0.6 - # - 2.0.7 - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - - name: Setup Poetry - uses: ./.github/actions/setup-poetry - with: - include_grpc: false - include_types: false - - - name: Install urllib3 ${{ matrix.urllib3-version }} - run: poetry add urllib3==${{ matrix.urllib3-version }} - - - uses: nick-fields/retry@v2 - with: - timeout_minutes: 5 - max_attempts: 3 - retry_on: error - command: poetry run pytest tests/dependency/rest -s -v - env: - PINECONE_API_KEY: ${{ secrets.PINECONE_API_KEY }} - INDEX_NAME: ${{ needs.dependency-matrix-rest-setup.outputs.index_name }} \ No newline at end of file diff --git a/.github/workflows/testing-unit.yaml b/.github/workflows/testing-unit.yaml new file mode 100644 index 000000000..f8026409c --- /dev/null +++ b/.github/workflows/testing-unit.yaml @@ -0,0 +1,37 @@ +name: "Unit Tests" +'on': + workflow_call: {} + +jobs: + unit-tests: + name: Unit tests + runs-on: ubuntu-latest + strategy: + matrix: + python-version: + - 3.8 + - 3.9 + - '3.10' + - 3.11 + use_grpc: + - true + - false + steps: + - uses: actions/checkout@v4 + - name: 'Set up Python ${{ matrix.python-version }}' + uses: actions/setup-python@v4 + with: + python-version: '${{ matrix.python-version }}' + - name: Setup Poetry + uses: ./.github/actions/setup-poetry + with: + include_grpc: '${{ matrix.use_grpc }}' + include_types: true + - name: Run unit tests + run: poetry run pytest --cov=pinecone --timeout=120 tests/unit + - name: mypy check + env: + INCLUDE_GRPC: '${{ matrix.use_grpc }}' + run: > + GRPC_FLAG=$( [ "$INCLUDE_GRPC" = "false" ] && echo "--exclude pinecone/grpc" || echo "" ) + poetry run mypy pinecone --exclude pinecone/core $GRPC_FLAG diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 5c1db1d80..6f7341b69 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -3,9 +3,10 @@ """ from .config import * from .exceptions import * -from .control.pinecone import Pinecone -from .data.index import * +from .control import * +from .data import * from .models import * + from .core.client.models import ( IndexModel, ) diff --git a/pinecone/control/__init__.py b/pinecone/control/__init__.py new file mode 100644 index 000000000..f083730e9 --- /dev/null +++ b/pinecone/control/__init__.py @@ -0,0 +1 @@ +from .pinecone import Pinecone \ No newline at end of file diff --git a/pinecone/data/__init__.py b/pinecone/data/__init__.py index a43d33ac4..5144527c6 100644 --- a/pinecone/data/__init__.py +++ b/pinecone/data/__init__.py @@ -1 +1,10 @@ -from .index import Index \ No newline at end of file +from .index import * +from .vector_factory import ( + VectorDictionaryMissingKeysError, + VectorDictionaryExcessKeysError, + VectorTupleLengthError, + SparseValuesTypeError, + SparseValuesMissingKeysError, + SparseValuesDictionaryExpectedError, + MetadataDictionaryExpectedError +) \ No newline at end of file diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 074365f74..a9f7b80f2 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -321,10 +321,10 @@ def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> Fe @validate_and_convert_errors def query( self, + top_k: int, vector: Optional[List[float]] = None, id: Optional[str] = None, queries: Optional[Union[List[QueryVector], List[Tuple]]] = None, - top_k: Optional[int] = None, namespace: Optional[str] = None, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index 0b38a8ca9..ff1f0bd69 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -24,10 +24,10 @@ def __init__(self, item): class VectorTupleLengthError(ValueError): def __init__(self, item): - message = f"Found a tuple of length {len(item)} which is not supported. Vectors can be represented as tuples either the form (id, values, metadata) or (id, values). To pass sparse values please use either dicts or a Vector objects as inputs." + message = f"Found a tuple of length {len(item)} which is not supported. Vectors can be represented as tuples either the form (id, values, metadata) or (id, values). To pass sparse values please use either dicts or Vector objects as inputs." super().__init__(message) -class SparseValuesTypeError(ValueError): +class SparseValuesTypeError(ValueError, TypeError): def __init__(self): message = "Found unexpected data in column `sparse_values`. Expected format is `'sparse_values': {'indices': List[int], 'values': List[float]}`." super().__init__(message) @@ -37,12 +37,12 @@ def __init__(self, sparse_values_dict): message = f"Missing required keys in data in column `sparse_values`. Expected format is `'sparse_values': {{'indices': List[int], 'values': List[float]}}`. Found keys {list(sparse_values_dict.keys())}" super().__init__(message) -class SparseValuesDictionaryExpectedError(ValueError): +class SparseValuesDictionaryExpectedError(ValueError, TypeError): def __init__(self, sparse_values_dict): message = f"Column `sparse_values` is expected to be a dictionary, found {type(sparse_values_dict)}" super().__init__(message) -class MetadataDictionaryExpectedError(ValueError): +class MetadataDictionaryExpectedError(ValueError, TypeError): def __init__(self, item): message = f"Column `metadata` is expected to be a dictionary, found {type(item['metadata'])}" super().__init__(message) @@ -64,7 +64,10 @@ def _tuple_to_vector(item, check_type: bool) -> Vector: if len(item) < 2 or len(item) > 3: raise VectorTupleLengthError(item) id, values, metadata = fix_tuple_length(item, 3) - return Vector(id=id, values=convert_to_list(values), metadata=metadata or {}, _check_type=check_type) + if isinstance(values, SparseValues): + raise ValueError("Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs.") + else: + return Vector(id=id, values=convert_to_list(values), metadata=metadata or {}, _check_type=check_type) @staticmethod def _dict_to_vector(item, check_type: bool) -> Vector: diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py index 5ba565ce8..71efa350a 100644 --- a/pinecone/grpc/__init__.py +++ b/pinecone/grpc/__init__.py @@ -1,2 +1,11 @@ from .index_grpc import GRPCIndex -from .pinecone import PineconeGRPC \ No newline at end of file +from .pinecone import PineconeGRPC + +from pinecone.core.grpc.protos.vector_service_pb2 import ( + Vector as GRPCVector, + QueryVector as GRPCQueryVector, + SparseValues as GRPCSparseValues, + Vector, + QueryVector, + SparseValues +) \ No newline at end of file diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index 47c9d3aac..e52dc9686 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -8,6 +8,7 @@ from tqdm.autonotebook import tqdm from .utils import dict_to_proto_struct, parse_fetch_response, parse_query_response, parse_stats_response +from .vector_factory_grpc import VectorFactoryGRPC from pinecone.core.client.models import ( FetchResponse, @@ -28,15 +29,13 @@ UpdateResponse, SparseValues as GRPCSparseValues, ) +from pinecone import Vector as NonGRPCVector from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub from pinecone.utils import fix_tuple_length -from pinecone.utils.constants import ( - REQUIRED_VECTOR_FIELDS, - OPTIONAL_VECTOR_FIELDS, -) from .base import GRPCIndexBase from .future import PineconeGrpcFuture + __all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] _logger = logging.getLogger(__name__) @@ -55,7 +54,7 @@ def stub_class(self): def upsert( self, - vectors: Union[List[GRPCVector], List[tuple], List[dict]], + vectors: Union[List[GRPCVector], List[NonGRPCVector], List[tuple], List[dict]], async_req: bool = False, namespace: Optional[str] = None, batch_size: Optional[int] = None, @@ -74,7 +73,7 @@ def upsert( >>> index.upsert([{'id': 'id1', 'values': [1.0, 2.0, 3.0], 'metadata': {'key': 'value'}}, {'id': 'id2', 'values': [1.0, 2.0, 3.0], - 'sprase_values': {'indices': [1, 8], 'values': [0.2, 0.4]}, + 'sparse_values': {'indices': [1, 8], 'values': [0.2, 0.4]}, ]) >>> index.upsert([GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), GRPCVector(id='id2', values=[1.0, 2.0, 3.0]), @@ -123,73 +122,9 @@ def upsert( "https://docs.pinecone.io/docs/performance-tuning" ) - def _dict_to_grpc_vector(item) -> GRPCVector: - item_keys = set(item.keys()) - if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): - raise ValueError( - f"Vector dictionary is missing required fields: {list(REQUIRED_VECTOR_FIELDS - item_keys)}" - ) - - excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) - if len(excessive_keys) > 0: - raise ValueError( - f"Found excess keys in the vector dictionary: {list(excessive_keys)}. " - f"The allowed keys are: {list(REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS)}" - ) - - sparse_values = None - if "sparse_values" in item: - if not isinstance(item["sparse_values"], Mapping): - raise TypeError( - f"Column `sparse_values` is expected to be a dictionary, found {type(item['sparse_values'])}" - ) - indices = item["sparse_values"].get("indices", None) - values = item["sparse_values"].get("values", None) - try: - sparse_values = GRPCSparseValues(indices=indices, values=values) - except TypeError as e: - raise TypeError( - "Found unexpected data in column `sparse_values`. " - "Expected format is `'sparse_values': {'indices': List[int], 'values': List[float]}`." - ) from e - - metadata = item.get("metadata", None) - if metadata is not None and not isinstance(metadata, Dict): - raise TypeError(f"Column `metadata` is expected to be a dictionary, found {type(metadata)}") - - try: - return GRPCVector( - id=item["id"], - values=item["values"], - sparse_values=sparse_values, - metadata=dict_to_proto_struct(metadata), - ) - - except TypeError as e: - # No need to raise a dedicated error for `id` - protobuf's error message is clear enough - if not isinstance(item["values"], Iterable) or not isinstance(item["values"].__iter__().__next__(), numbers.Real): - raise TypeError(f"Column `values` is expected to be a list of floats") - raise - - def _vector_transform(item) -> GRPCVector: - if isinstance(item, GRPCVector): - return item - elif isinstance(item, tuple): - if len(item) > 3: - raise ValueError( - f"Found a tuple of length {len(item)} which is not supported. " - f"Vectors can be represented as tuples either the form (id, values, metadata) or (id, values). " - f"To pass sparse values please use either dicts or GRPCVector objects as inputs." - ) - id, values, metadata = fix_tuple_length(item, 3) - return GRPCVector(id=id, values=values, metadata=dict_to_proto_struct(metadata)) - elif isinstance(item, Mapping): - return _dict_to_grpc_vector(item) - raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") - timeout = kwargs.pop("timeout", None) - vectors = list(map(_vector_transform, vectors)) + vectors = list(map(VectorFactoryGRPC.build, vectors)) if async_req: args_dict = self._parse_non_empty_args([("namespace", namespace)]) request = UpsertRequest(vectors=vectors, **args_dict, **kwargs) diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index 4e8057ecd..6ca64f3db 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -41,20 +41,24 @@ def parse_sparse_values(sparse_values: dict): def parse_fetch_response(response: dict): vd = {} - vectors = response.get("vectors") - if not vectors: - return None + vectors = response.get("vectors", {}) + namespace = response.get("namespace", "") + for id, vec in vectors.items(): - v_obj = _Vector( + vd[id] = _Vector( id=vec["id"], values=vec["values"], sparse_values=parse_sparse_values(vec.get("sparseValues")), metadata=vec.get("metadata", None), _check_type=False, ) - vd[id] = v_obj - namespace = response.get("namespace", "") - return FetchResponse(vectors=vd, namespace=namespace, _check_type=False) + + return FetchResponse( + vectors=vd, + namespace=namespace, + _check_type=False + ) + def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): @@ -71,7 +75,7 @@ def parse_query_response(response: dict, unary_query: bool, _check_type: bool = score=item.get("score", 0.0), values=item.get("values", []), sparse_values=parse_sparse_values(item.get("sparseValues")), - metadata=item.get("metadata", {}), + metadata=item.get("metadata", None), ) m.append(sc) res.append(SingleQueryResults(matches=m, namespace=namespace)) @@ -83,7 +87,7 @@ def parse_query_response(response: dict, unary_query: bool, _check_type: bool = score=item.get("score", 0.0), values=item.get("values", []), sparse_values=parse_sparse_values(item.get("sparseValues")), - metadata=item.get("metadata", {}), + metadata=item.get("metadata", None), _check_type=_check_type, ) m.append(sc) diff --git a/pinecone/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py new file mode 100644 index 000000000..c1ff3c097 --- /dev/null +++ b/pinecone/grpc/vector_factory_grpc.py @@ -0,0 +1,122 @@ +import numbers + +from collections.abc import Iterable, Mapping +from typing import Union, Tuple, Dict + +from google.protobuf.struct_pb2 import Struct + +from .utils import dict_to_proto_struct +from ..utils import fix_tuple_length, convert_to_list +from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS +from ..data import ( + VectorDictionaryMissingKeysError, + VectorDictionaryExcessKeysError, + VectorTupleLengthError, + SparseValuesTypeError, + SparseValuesMissingKeysError, + SparseValuesDictionaryExpectedError, + MetadataDictionaryExpectedError +) + +from pinecone.core.grpc.protos.vector_service_pb2 import ( + Vector as GRPCVector, + QueryVector as GRPCQueryVector, + SparseValues as GRPCSparseValues, +) +from pinecone import ( + Vector as NonGRPCVector, + SparseValues as NonGRPCSparseValues +) + +class VectorFactoryGRPC: + @staticmethod + def build(item: Union[GRPCVector, NonGRPCVector, Tuple, Dict]) -> GRPCVector: + if isinstance(item, GRPCVector): + return item + elif isinstance(item, NonGRPCVector): + if item.sparse_values: + sv = GRPCSparseValues(indices=item.sparse_values.indices, values=item.sparse_values.values) + return GRPCVector(id=item.id, values=item.values, metadata=dict_to_proto_struct(item.metadata or {}), sparse_values=sv) + else: + return GRPCVector(id=item.id, values=item.values, metadata=dict_to_proto_struct(item.metadata or {})) + elif isinstance(item, tuple): + return VectorFactoryGRPC._tuple_to_vector(item) + elif isinstance(item, Mapping): + return VectorFactoryGRPC._dict_to_vector(item) + else: + raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + + @staticmethod + 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): + raise ValueError("Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs.") + else: + return GRPCVector(id=id, values=convert_to_list(values), metadata=dict_to_proto_struct(metadata or {})) + + @staticmethod + def _dict_to_vector(item) -> GRPCVector: + item_keys = set(item.keys()) + if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): + raise VectorDictionaryMissingKeysError(item) + + excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) + if len(excessive_keys) > 0: + raise VectorDictionaryExcessKeysError(item) + + values = item.get("values") + if "values" in item: + try: + item["values"] = convert_to_list(values) + except TypeError as e: + raise TypeError(f"Column `values` is expected to be a list of floats") from e + + sparse_values = item.get("sparse_values") + if sparse_values and not isinstance(sparse_values, GRPCSparseValues): + item["sparse_values"] = VectorFactoryGRPC._dict_to_sparse_values(sparse_values) + + metadata = item.get("metadata") + if metadata: + if isinstance(metadata, dict): + item["metadata"] = dict_to_proto_struct(metadata) + elif not isinstance(metadata, Struct): + raise MetadataDictionaryExpectedError(item) + else: + item["metadata"] = dict_to_proto_struct({}) + + try: + return GRPCVector(**item) + except TypeError as e: + if not isinstance(item["values"], Iterable) or not isinstance(item["values"].__iter__().__next__(), numbers.Real): + raise TypeError(f"Column `values` is expected to be a list of floats") + raise e + + @staticmethod + def _dict_to_sparse_values(sparse_values_dict: Union[Dict, GRPCSparseValues, NonGRPCSparseValues]) -> GRPCSparseValues: + if isinstance(sparse_values_dict, GRPCSparseValues): + return sparse_values_dict + if isinstance(sparse_values_dict, NonGRPCSparseValues): + return GRPCSparseValues(indices=sparse_values_dict.indices, values=sparse_values_dict.values) + + if not isinstance(sparse_values_dict, Mapping): + raise SparseValuesDictionaryExpectedError(sparse_values_dict) + if not {"indices", "values"}.issubset(sparse_values_dict): + raise SparseValuesMissingKeysError(sparse_values_dict) + + + try: + indices = convert_to_list(sparse_values_dict.get("indices")) + except TypeError as e: + raise SparseValuesTypeError() from e + + try: + values = convert_to_list(sparse_values_dict.get("values")) + except TypeError as e: + raise SparseValuesTypeError() from e + + try: + return GRPCSparseValues(indices=indices, values=values) + except TypeError as e: + raise SparseValuesTypeError() from e \ No newline at end of file diff --git a/pinecone/utils/convert_to_list.py b/pinecone/utils/convert_to_list.py index ecaf45902..ce28a9f5d 100644 --- a/pinecone/utils/convert_to_list.py +++ b/pinecone/utils/convert_to_list.py @@ -3,7 +3,7 @@ def convert_to_list(obj): if class_name == 'list': return obj - elif hasattr(obj, 'tolist'): + elif hasattr(obj, 'tolist') and callable(getattr(obj, 'tolist')): return obj.tolist() else: return list(obj) \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index ebcb3b4e3..86aabad9c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1198,4 +1198,4 @@ grpc = ["googleapis-common-protos", "grpc-gateway-protoc-gen-openapiv2", "grpcio [metadata] lock-version = "2.0" python-versions = ">=3.8,<3.13" -content-hash = "e9c4475c8166329908aba5405167a0c79c0c108634b0b15a0ec37231c997e705" +content-hash = "9b463283ead14a000789fdc1d8ef0797759103b326dea21a2ae07083011ba2ad" diff --git a/tests/integration/control/__init__.py b/tests/integration/control/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/conftest.py b/tests/integration/control/conftest.py similarity index 98% rename from tests/integration/conftest.py rename to tests/integration/control/conftest.py index 0abe1296f..b43bde998 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/control/conftest.py @@ -3,7 +3,7 @@ import random import time from pinecone import Pinecone, NotFoundException, PineconeApiException -from .helpers.helpers import generate_index_name, get_environment_var +from ..helpers import generate_index_name, get_environment_var @pytest.fixture() def client(): diff --git a/tests/integration/test_collections.py b/tests/integration/control/test_collections.py similarity index 100% rename from tests/integration/test_collections.py rename to tests/integration/control/test_collections.py diff --git a/tests/integration/test_create_index_api_errors.py b/tests/integration/control/test_create_index_api_errors.py similarity index 100% rename from tests/integration/test_create_index_api_errors.py rename to tests/integration/control/test_create_index_api_errors.py diff --git a/tests/integration/test_create_index_sl_happy_path.py b/tests/integration/control/test_create_index_sl_happy_path.py similarity index 100% rename from tests/integration/test_create_index_sl_happy_path.py rename to tests/integration/control/test_create_index_sl_happy_path.py diff --git a/tests/integration/test_create_index_timeouts.py b/tests/integration/control/test_create_index_timeouts.py similarity index 100% rename from tests/integration/test_create_index_timeouts.py rename to tests/integration/control/test_create_index_timeouts.py diff --git a/tests/integration/test_create_index_type_errors.py b/tests/integration/control/test_create_index_type_errors.py similarity index 100% rename from tests/integration/test_create_index_type_errors.py rename to tests/integration/control/test_create_index_type_errors.py diff --git a/tests/integration/test_describe_index.py b/tests/integration/control/test_describe_index.py similarity index 100% rename from tests/integration/test_describe_index.py rename to tests/integration/control/test_describe_index.py diff --git a/tests/integration/test_list_indexes.py b/tests/integration/control/test_list_indexes.py similarity index 100% rename from tests/integration/test_list_indexes.py rename to tests/integration/control/test_list_indexes.py diff --git a/tests/integration/data/__init__.py b/tests/integration/data/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/data/conftest.py b/tests/integration/data/conftest.py new file mode 100644 index 000000000..c3828e170 --- /dev/null +++ b/tests/integration/data/conftest.py @@ -0,0 +1,83 @@ +import pytest +import os +import time +import json +from ..helpers import get_environment_var, random_string +from .seed import setup_data + +# 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 + +def api_key(): + return get_environment_var('PINECONE_API_KEY') + +def use_grpc(): + return os.environ.get('USE_GRPC', 'false') == 'true' + +def build_client(): + if use_grpc(): + from pinecone.grpc import PineconeGRPC + return PineconeGRPC(api_key=api_key()) + else: + from pinecone import Pinecone + return Pinecone(api_key=api_key()) + +@pytest.fixture(scope='session') +def client(): + return build_client() + +@pytest.fixture(scope='session') +def metric(): + return get_environment_var('METRIC', 'cosine') + +@pytest.fixture(scope='session') +def spec(): + return json.loads(get_environment_var('SPEC')) + +@pytest.fixture(scope='session') +def index_name(): + # return 'dataplane-lol' + return 'dataplane-' + random_string(20) + +@pytest.fixture(scope='session') +def namespace(): + # return 'banana' + return random_string(10) + +@pytest.fixture(scope='session') +def idx(client, index_name, index_host): + return client.Index(name=index_name, host=index_host) + +@pytest.fixture(scope='session') +def index_host(index_name, metric, spec): + pc = build_client() + print('Creating index with name: ' + index_name) + pc.create_index( + name=index_name, + dimension=2, + metric=metric, + spec=spec + ) + description = pc.describe_index(name=index_name) + yield description.host + print('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): + print('Seeding data in host ' + index_host) + + print('Seeding data in namespace "' + namespace + '"') + setup_data(idx, namespace, False) + + print('Seeding data in namespace ""') + setup_data(idx, '', True) + + print('Waiting a bit more to ensure freshness') + time.sleep(60) + yield \ No newline at end of file diff --git a/tests/integration/data/seed.py b/tests/integration/data/seed.py new file mode 100644 index 000000000..cb5c037bc --- /dev/null +++ b/tests/integration/data/seed.py @@ -0,0 +1,34 @@ +from ..helpers import poll_fetch_for_ids_in_namespace +from pinecone import Vector +from .utils import embedding_values + +def setup_data(idx, target_namespace, wait): + # Upsert without metadata + idx.upsert(vectors=[ + ('1', embedding_values(2)), + ('2', embedding_values(2)), + ('3', embedding_values(2)) + ], + namespace=target_namespace + ) + + # Upsert 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=target_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=target_namespace + ) + + if wait: + poll_fetch_for_ids_in_namespace(idx, ids=['1', '2', '3', '4', '5', '6', '7', '8', '9'], namespace=target_namespace) diff --git a/tests/integration/data/test_fetch.py b/tests/integration/data/test_fetch.py new file mode 100644 index 000000000..feef6b5f5 --- /dev/null +++ b/tests/integration/data/test_fetch.py @@ -0,0 +1,79 @@ +import pytest +from pinecone import PineconeException, FetchResponse + +class TestFetch: + 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 '' + + results = idx.fetch(ids=['1', '2', '4'], namespace=target_namespace) + assert isinstance(results, FetchResponse) == True + assert results.namespace == target_namespace + assert len(results.vectors) == 3 + assert results.vectors['1'].id == '1' + assert results.vectors['2'].id == '2' + # Metadata included, if set + assert results.vectors['1'].metadata == None + assert results.vectors['2'].metadata == None + assert results.vectors['4'].metadata != None + assert results.vectors['4'].metadata['genre'] == 'action' + assert results.vectors['4'].metadata['runtime'] == 120 + # Values included + assert results.vectors['1'].values != None + 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 '' + + results = idx.fetch(ids=['1'], namespace=target_namespace) + assert results.namespace == target_namespace + assert len(results.vectors) == 1 + assert results.vectors['1'].id == '1' + assert results.vectors['1'].metadata == None + assert results.vectors['1'].values != None + 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 '' + + # Fetch id that is missing + results = idx.fetch(ids=['100'], namespace=target_namespace) + assert results.namespace == target_namespace + assert len(results.vectors) == 0 + + def test_fetch_nonexistent_namespace(self, idx): + target_namespace = 'nonexistent-namespace' + + # Fetch from namespace with no vectors + results = idx.fetch(ids=['1'], namespace=target_namespace) + assert results.namespace == target_namespace + 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 '' + + # Fetch with empty list of ids + with pytest.raises(PineconeException) as e: + idx.fetch(ids=[], namespace=target_namespace) + assert 'ids' in str(e.value).lower() + + def test_fetch_unspecified_namespace(self, idx): + # Fetch without specifying namespace gives default namespace results + results = idx.fetch(ids=['1', '4']) + assert results.namespace == '' + assert results.vectors['1'].id == '1' + assert results.vectors['1'].values != None + assert results.vectors['4'].metadata != None + diff --git a/tests/integration/data/test_query.py b/tests/integration/data/test_query.py new file mode 100644 index 000000000..45a83a695 --- /dev/null +++ b/tests/integration/data/test_query.py @@ -0,0 +1,189 @@ +import pytest +from pinecone import QueryResponse +from .utils import embedding_values + +def find_by_id(matches, id): + with_id = [match for match in matches if match.id == id] + return with_id[0] if len(with_id) > 0 else None + +@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 '' + + results = idx.query(id='1', namespace=target_namespace, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + + # TODO fix usage + # assert results.usage != None + + # By default, does not include values or metadata + record_with_metadata = find_by_id(results.matches, '4') + assert record_with_metadata.metadata == 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 '' + + 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 '' + + results = idx.query(vector=embedding_values(2), namespace=target_namespace, include_values=True, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) > 0 + assert results.matches[0].values != 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 '' + + results = idx.query(vector=embedding_values(2), namespace=target_namespace, include_metadata=True, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + + matches_with_metadata = [match for match in results.matches if match.metadata != None] + assert len(matches_with_metadata) == 3 + 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): + target_namespace = namespace if use_nondefault_namespace else '' + + results = idx.query(vector=embedding_values(2), namespace=target_namespace, include_values=True, include_metadata=True, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + + matches_with_metadata = [match for match in results.matches if match.metadata != None] + assert len(matches_with_metadata) == 3 + assert find_by_id(results.matches, '4').metadata['genre'] == 'action' + assert len(results.matches[0].values) == self.expected_dimension + +class TestQueryEdgeCases(): + def test_query_in_empty_namespace(self, idx): + results = idx.query(id='1', namespace='empty', top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == 'empty' + assert len(results.matches) == 0 + +@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 '' + + results = idx.query(id='1', namespace=target_namespace, filter={'genre': 'action'}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_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 '' + + # 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 }) + results = idx.query(id='1', namespace=target_namespace, filter={'runtime': {'$gt': 100}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 2 + assert find_by_id(results.matches, '4') != None + assert find_by_id(results.matches, '6') != None + + def test_query_by_id_with_filter_gte(self, idx, namespace, use_nondefault_namespace): + target_namespace = 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 }), + # Vector(id='6', values=embedding_values(2), metadata={'genre': 'romance', 'runtime': 240 }) + results = idx.query(id='1', namespace=target_namespace, filter={'runtime': {'$gte': 90}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 3 + assert find_by_id(results.matches, '4') != None + assert find_by_id(results.matches, '5') != None + assert find_by_id(results.matches, '6') != None + + def test_query_by_id_with_filter_lt(self, idx, namespace, use_nondefault_namespace): + target_namespace = 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 }), + # Vector(id='6', values=embedding_values(2), metadata={'genre': 'romance', 'runtime': 240 }) + results = idx.query(id='1', namespace=target_namespace, filter={'runtime': {'$lt': 100}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 1 + assert find_by_id(results.matches, '5') != None + + def test_query_by_id_with_filter_lte(self, idx, namespace, use_nondefault_namespace): + target_namespace = 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 }), + # Vector(id='6', values=embedding_values(2), metadata={'genre': 'romance', 'runtime': 240 }) + results = idx.query(id='1', namespace=target_namespace, filter={'runtime': {'$lte': 120}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 2 + assert find_by_id(results.matches, '4') != None + assert find_by_id(results.matches, '5') != None + + def test_query_by_id_with_filter_in(self, idx, namespace, use_nondefault_namespace): + target_namespace = 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 }), + # Vector(id='6', values=embedding_values(2), metadata={'genre': 'romance', 'runtime': 240 }) + results = idx.query(id='1', namespace=target_namespace, filter={'genre': {'$in': ['romance']}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 1 + assert find_by_id(results.matches, '6') != 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 '' + + # 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 }) + results = idx.query(id='1', namespace=target_namespace, filter={'genre': {'$nin': ['romance']}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 2 + assert find_by_id(results.matches, '4') != None + assert find_by_id(results.matches, '5') != None + + def test_query_by_id_with_filter_eq(self, idx, namespace, use_nondefault_namespace): + target_namespace = 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 }), + # Vector(id='6', values=embedding_values(2), metadata={'genre': 'romance', 'runtime': 240 }) + results = idx.query(id='1', namespace=target_namespace, filter={'genre': {'$eq': 'action'}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 1 + assert find_by_id(results.matches, '4') != 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 '' + + # 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 }) + results = idx.query(id='1', namespace=target_namespace, filter={'genre': {'$ne': 'action'}}, top_k=10) + assert isinstance(results, QueryResponse) == True + assert results.namespace == target_namespace + assert len(results.matches) == 2 + assert find_by_id(results.matches, '5') != None + assert find_by_id(results.matches, '6') != None diff --git a/tests/integration/data/test_query_errors.py b/tests/integration/data/test_query_errors.py new file mode 100644 index 000000000..2a9aea599 --- /dev/null +++ b/tests/integration/data/test_query_errors.py @@ -0,0 +1,33 @@ +import pytest +from pinecone import PineconeException + +@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 '' + + 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 '' + + with pytest.raises(TypeError) as e: + 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 '' + + with pytest.raises((PineconeException, ValueError)) as e: + 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 '' + + with pytest.raises((TypeError, PineconeException)) as e: + idx.query(id='1', namespace=target_namespace) + + assert 'top_k' in str(e.value).lower() + diff --git a/tests/integration/data/test_upsert.py b/tests/integration/data/test_upsert.py new file mode 100644 index 000000000..5105c9cb3 --- /dev/null +++ b/tests/integration/data/test_upsert.py @@ -0,0 +1,86 @@ +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_errors.py b/tests/integration/data/test_upsert_errors.py new file mode 100644 index 000000000..fcc2e50fc --- /dev/null +++ b/tests/integration/data/test_upsert_errors.py @@ -0,0 +1,187 @@ +import pytest +import os +from pinecone import Vector, SparseValues +from .utils import embedding_values +from ..helpers import fake_api_key +from pinecone import PineconeException + +class TestUpsertApiKeyMissing(): + def test_upsert_fails_when_api_key_invalid(self, index_name, index_host): + with pytest.raises(PineconeException): + from pinecone import Pinecone + pc = Pinecone(api_key=fake_api_key()) + idx = pc.Index(name=index_name, host=index_host) + idx.upsert(vectors=[ + Vector(id='1', values=embedding_values()), + Vector(id='2', values=embedding_values()) + ] + ) + @pytest.mark.skipif(os.getenv('USE_GRPC') != 'true', reason='Only test grpc client when grpc extras') + def test_upsert_fails_when_api_key_invalid_grpc(self, index_name, index_host): + with pytest.raises(PineconeException): + from pinecone.grpc import PineconeGRPC + pc = PineconeGRPC(api_key=fake_api_key()) + idx = pc.Index(name=index_name, host=index_host) + idx.upsert(vectors=[ + Vector(id='1', values=embedding_values()), + Vector(id='2', values=embedding_values()) + ] + ) + +class TestUpsertFailsWhenDimensionMismatch(): + def test_upsert_fails_when_dimension_mismatch_objects(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + Vector(id='1', values=embedding_values(2)), + Vector(id='2', values=embedding_values(3)) + ]) + + def test_upsert_fails_when_dimension_mismatch_tuples(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + ('1', embedding_values(2)), + ('2', embedding_values(3)) + ]) + + def test_upsert_fails_when_dimension_mismatch_dicts(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + {'id': '1', 'values': embedding_values(2)}, + {'id': '2', 'values': embedding_values(3)} + ]) + +@pytest.mark.skipif(os.getenv('METRIC') != 'dotproduct', reason='Only metric=dotprodouct indexes support hybrid') +class TestUpsertFailsSparseValuesDimensionMismatch(): + def test_upsert_fails_when_sparse_values_indices_values_mismatch_objects(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + Vector(id='1', values=[0.1, 0.1], sparse_values=SparseValues(indices=[0], values=[0.5, 0.5])) + ]) + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + Vector(id='1', values=[0.1, 0.1], sparse_values=SparseValues(indices=[0, 1], values=[0.5])) + ]) + + def test_upsert_fails_when_sparse_values_in_tuples(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors=[ + ('1', SparseValues(indices=[0], values=[0.5])), + ('2', SparseValues(indices=[0, 1, 2], values=[0.5, 0.5, 0.5])) + ]) + + def test_upsert_fails_when_sparse_values_indices_values_mismatch_dicts(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + {'id': '1', 'values': [0.2, 0.2], 'sparse_values': SparseValues(indices=[0], values=[0.5, 0.5])} + ]) + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + {'id': '1', 'values': [0.1, 0.2], 'sparse_values': SparseValues(indices=[0, 1], values=[0.5])} + ]) + +class TestUpsertFailsWhenValuesMissing(): + def test_upsert_fails_when_values_missing_objects(self, idx): + with pytest.raises(TypeError): + idx.upsert(vectors=[ + Vector(id='1'), + Vector(id='2') + ]) + + def test_upsert_fails_when_values_missing_tuples(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors=[ + ('1',), + ('2',) + ]) + + def test_upsert_fails_when_values_missing_dicts(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors=[ + {'id': '1'}, + {'id': '2'} + ]) + +class TestUpsertFailsWhenValuesWrongType(): + def test_upsert_fails_when_values_wrong_type_objects(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[ + Vector(id='1', values='abc'), + Vector(id='2', values='def') + ]) + + def test_upsert_fails_when_values_wrong_type_tuples(self, idx): + if os.environ.get('USE_GRPC', 'false') == 'true': + expected_exception = TypeError + else: + expected_exception = PineconeException + + with pytest.raises(expected_exception): + idx.upsert(vectors=[ + ('1', 'abc'), + ('2', 'def') + ]) + + def test_upsert_fails_when_values_wrong_type_dicts(self, idx): + with pytest.raises(TypeError): + idx.upsert(vectors=[ + {'id': '1', 'values': 'abc'}, + {'id': '2', 'values': 'def'} + ]) + +class TestUpsertFailsWhenVectorsMissing(): + def test_upsert_fails_when_vectors_empty(self, idx): + with pytest.raises(PineconeException): + idx.upsert(vectors=[]) + + def test_upsert_fails_when_vectors_wrong_type(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors='abc') + + def test_upsert_fails_when_vectors_missing(self, idx): + with pytest.raises(TypeError): + idx.upsert() + +class TestUpsertIdMissing(): + def test_upsert_fails_when_id_is_missing_objects(self, idx): + with pytest.raises(TypeError): + idx.upsert(vectors=[ + Vector(id='1', values=embedding_values()), + Vector(values=embedding_values()) + ]) + + def test_upsert_fails_when_id_is_missing_tuples(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors=[ + ('1', embedding_values()), + (embedding_values()) + ]) + + def test_upsert_fails_when_id_is_missing_dicts(self, idx): + with pytest.raises(ValueError): + idx.upsert(vectors=[ + {'id': '1', 'values': embedding_values()}, + {'values': embedding_values()} + ]) + + +class TestUpsertIdWrongType(): + def test_upsert_fails_when_id_wrong_type_objects(self, idx): + with pytest.raises(Exception): + idx.upsert(vectors=[ + Vector(id='1', values=embedding_values()), + Vector(id=2, values=embedding_values()) + ]) + + def test_upsert_fails_when_id_wrong_type_tuples(self, idx): + with pytest.raises(Exception): + idx.upsert(vectors=[ + ('1', embedding_values()), + (2, embedding_values()) + ]) + + def test_upsert_fails_when_id_wrong_type_dicts(self, idx): + with pytest.raises(Exception): + idx.upsert(vectors=[ + {'id': '1', 'values': embedding_values()}, + {'id': 2, 'values': embedding_values()} + ]) \ No newline at end of file diff --git a/tests/integration/data/utils.py b/tests/integration/data/utils.py new file mode 100644 index 000000000..8023ce226 --- /dev/null +++ b/tests/integration/data/utils.py @@ -0,0 +1,5 @@ +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 e69de29bb..6914ce1ca 100644 --- a/tests/integration/helpers/__init__.py +++ b/tests/integration/helpers/__init__.py @@ -0,0 +1,8 @@ +from .helpers import ( + fake_api_key, + get_environment_var, + random_string, + generate_index_name, + poll_stats_for_namespace, + poll_fetch_for_ids_in_namespace +) \ No newline at end of file diff --git a/tests/integration/helpers/helpers.py b/tests/integration/helpers/helpers.py index 1d19e8239..e7da0173c 100644 --- a/tests/integration/helpers/helpers.py +++ b/tests/integration/helpers/helpers.py @@ -1,5 +1,6 @@ import re import os +import time import random import string from typing import Any @@ -44,3 +45,41 @@ def get_environment_var(name: str, defaultVal: Any = None) -> str: raise Exception('Expected environment variable ' + name + ' is not set') else: return val + +def poll_stats_for_namespace(idx, namespace, expected_count, max_sleep=int(os.environ.get('FRESHNESS_TIMEOUT_SECONDS', 60))): + delta_t = 5 + total_time=0 + done = False + while not done: + print(f'Waiting for namespace "{namespace}" to have vectors. Total time waited: {total_time} seconds') + stats = idx.describe_index_stats() + if namespace in stats.namespaces and stats.namespaces[namespace].vector_count >= expected_count: + done = True + elif total_time > max_sleep: + raise TimeoutError(f'Timed out waiting for namespace {namespace} to have vectors') + else: + total_time += delta_t + time.sleep(delta_t) + +def poll_fetch_for_ids_in_namespace(idx, ids, namespace): + max_sleep=int(os.environ.get('FRESHNESS_TIMEOUT_SECONDS', 60)) + delta_t = 5 + total_time=0 + done = False + while not done: + print(f'Attempting to fetch from "{namespace}". Total time waited: {total_time} seconds') + results = idx.fetch(ids=ids, namespace=namespace) + print(results) + + all_present = all(key in results.vectors for key in ids) + if all_present: + done = True + + if total_time > max_sleep: + raise TimeoutError(f'Timed out waiting for namespace {namespace} to have vectors') + else: + total_time += delta_t + time.sleep(delta_t) + +def fake_api_key(): + return '-'.join([random_string(x) for x in [8, 4, 4, 4, 12]]) \ No newline at end of file diff --git a/tests/unit/utils/test_convert_to_list.py b/tests/unit/utils/test_convert_to_list.py index 88efc0e3b..384e169f1 100644 --- a/tests/unit/utils/test_convert_to_list.py +++ b/tests/unit/utils/test_convert_to_list.py @@ -1,5 +1,6 @@ import pytest from pinecone.utils import convert_to_list +from pinecone import SparseValues import numpy as np import pandas as pd diff --git a/tests/unit_grpc/conftest.py b/tests/unit_grpc/conftest.py new file mode 100644 index 000000000..bb1641954 --- /dev/null +++ b/tests/unit_grpc/conftest.py @@ -0,0 +1,55 @@ +import pytest + + +@pytest.fixture +def vector_dim(): + return 8 + +@pytest.fixture +def vals1(vector_dim): + return [0.1] * vector_dim + + +@pytest.fixture +def vals2(vector_dim): + return [0.2] * vector_dim + + +@pytest.fixture +def sparse_indices_1(): + return [1, 8, 42] + + +@pytest.fixture +def sparse_values_1(): + return [0.8, 0.9, 0.42] + + +@pytest.fixture +def sparse_indices_2(): + return [1, 3, 5] + + +@pytest.fixture +def sparse_values_2(): + return [0.7, 0.3, 0.31415] + + +@pytest.fixture +def md1(): + return {"genre": "action", "year": 2021} + + +@pytest.fixture +def md2(): + return {"genre": "documentary", "year": 2020} + + +@pytest.fixture +def filter1(): + return {"genre": {"$in": ["action"]}} + + +@pytest.fixture +def filter2(): + return {"year": {"$eq": 2020}} diff --git a/tests/unit_grpc/test_grpc_index.py b/tests/unit_grpc/test_grpc_index.py deleted file mode 100644 index b797fd26b..000000000 --- a/tests/unit_grpc/test_grpc_index.py +++ /dev/null @@ -1,694 +0,0 @@ -from copy import deepcopy - -import numpy as np -import pandas as pd -import pytest - -from pinecone import Config -from pinecone.grpc import GRPCIndex -from pinecone import DescribeIndexStatsRequest -from pinecone.core.grpc.protos.vector_service_pb2 import ( - Vector, - DescribeIndexStatsRequest, - UpdateRequest, - UpsertRequest, - FetchRequest, - QueryRequest, - DeleteRequest, - QueryVector, - UpsertResponse, - SparseValues, -) -from pinecone.grpc.utils import dict_to_proto_struct - -class TestGrpcIndex: - def setup_method(self): - self.vector_dim = 8 - self.vals1 = [0.1] * self.vector_dim - self.vals2 = [0.2] * self.vector_dim - self.sparse_indices_1 = [1, 8, 42] - self.sparse_values_1 = [0.8, 0.9, 0.42] - self.sparse_indices_2 = [1, 3, 5] - self.sparse_values_2 = [0.7, 0.3, 0.31415] - self.md1 = {"genre": "action", "year": 2021} - self.md2 = {"genre": "documentary", "year": 2020} - self.filter1 = {"genre": {"$in": ["action"]}} - self.filter2 = {"year": {"$eq": 2020}} - - self.config = Config(api_key='test-api-key', host='foo') - self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") - - self.expected_vec1 = Vector(id="vec1", values=self.vals1, metadata={}) - self.expected_vec2 = Vector(id="vec2", values=self.vals2, metadata={}) - self.expected_vec_md1 = Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1)) - self.expected_vec_md2 = Vector(id="vec2", values=self.vals2, metadata=dict_to_proto_struct(self.md2)) - self.expected_vec_md_sparse1 = Vector( - id="vec1", - values=self.vals1, - metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), - ) - self.expected_vec_md_sparse2 = Vector( - id="vec2", - values=self.vals2, - metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), - ) - - # region: upsert tests - - def _assert_called_once(self, vectors, async_call=False): - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Upsert.future if async_call else self.index.stub.Upsert, - UpsertRequest(vectors=vectors, namespace="ns"), - timeout=None, - ) - - def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.upsert([("vec1", self.vals1), ("vec2", self.vals2)], namespace="ns") - self._assert_called_once([self.expected_vec1, self.expected_vec2]) - - def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.upsert([("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2)], namespace="ns") - self._assert_called_once( - [self.expected_vec_md1, self.expected_vec_md2], - ) - - def test_upsert_vectors_upsertInputVectors(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns") - self._assert_called_once( - [self.expected_vec_md1, self.expected_vec_md2], - ) - - def test_upsert_vectors_upsertInputVectorsSparse(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.upsert( - [ - Vector( - id="vec1", - values=self.vals1, - metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), - ), - Vector( - id="vec2", - values=self.vals2, - metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), - ), - ], - namespace="ns", - ) - self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2]) - - def test_upsert_dict(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - dict1 = {"id": "vec1", "values": self.vals1} - dict2 = {"id": "vec2", "values": self.vals2} - self.index.upsert([dict1, dict2], namespace="ns") - self._assert_called_once([self.expected_vec1, self.expected_vec2]) - - def test_upsert_dict_md(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - dict1 = {"id": "vec1", "values": self.vals1, "metadata": self.md1} - dict2 = {"id": "vec2", "values": self.vals2, "metadata": self.md2} - self.index.upsert([dict1, dict2], namespace="ns") - self._assert_called_once([self.expected_vec_md1, self.expected_vec_md2]) - - def test_upsert_dict_sparse(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - } - dict2 = { - "id": "vec2", - "values": self.vals2, - "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, - } - self.index.upsert([dict1, dict2], namespace="ns") - self._assert_called_once( - [ - Vector( - id="vec1", - values=self.vals1, - metadata={}, - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), - ), - Vector( - id="vec2", - values=self.vals2, - metadata={}, - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), - ), - ] - ) - - def test_upsert_dict_sparse_md(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - } - dict2 = { - "id": "vec2", - "values": self.vals2, - "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, - "metadata": self.md2, - } - self.index.upsert([dict1, dict2], namespace="ns") - self._assert_called_once( - [ - Vector( - id="vec1", - values=self.vals1, - metadata=dict_to_proto_struct(self.md1), - sparse_values=SparseValues(indices=self.sparse_indices_1, values=self.sparse_values_1), - ), - Vector( - id="vec2", - values=self.vals2, - metadata=dict_to_proto_struct(self.md2), - sparse_values=SparseValues(indices=self.sparse_indices_2, values=self.sparse_values_2), - ), - ] - ) - - def test_upsert_dict_negative(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - - # Missing required keys - dict1 = {"values": self.vals1} - dict2 = {"id": "vec2"} - with pytest.raises(ValueError): - self.index.upsert([dict1, dict2]) - with pytest.raises(ValueError): - self.index.upsert([dict1]) - with pytest.raises(ValueError): - self.index.upsert([dict2]) - - # Excess keys - dict1 = {"id": "vec1", "values": self.vals1} - dict2 = {"id": "vec2", "values": self.vals2, "animal": "dog"} - with pytest.raises(ValueError) as e: - self.index.upsert([dict1, dict2]) - assert "animal" in str(e.value) - - dict1 = {"id": "vec1", "values": self.vals1, "metadatta": self.md2} - dict2 = {"id": "vec2", "values": self.vals2} - with pytest.raises(ValueError) as e: - self.index.upsert([dict1, dict2]) - assert "metadatta" in str(e.value) - - @pytest.mark.parametrize( - "key,new_val", - [ - ("values", ["the", "lazy", "fox"]), - ("values", "the lazy fox"), - ("values", 0.5), - ("metadata", np.nan), - ("metadata", ["key1", "key2"]), - ("sparse_values", "cat"), - ("sparse_values", []), - ], - ) - def test_upsert_dict_with_invalid_values(self, mocker, key, new_val): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - - full_dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - } - - dict1 = deepcopy(full_dict1) - dict1[key] = new_val - with pytest.raises(TypeError) as e: - self.index.upsert([dict1]) - assert key 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): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - - full_dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - } - - dict1 = deepcopy(full_dict1) - dict1[key] = new_val - with pytest.raises(TypeError) as e: - self.index.upsert([dict1]) - assert str(new_val) in str(e.value) - - @pytest.mark.parametrize( - "key,new_val", - [ - ("indices", 3), - ("indices", [1.2, 0.5]), - ("values", ["1", "4.4"]), - ("values", 0.5), - ], - ) - def test_upsert_dict_with_invalid_sparse_values(self, mocker, key, new_val): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - - full_dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - } - - dict1 = deepcopy(full_dict1) - dict1["sparse_values"][key] = new_val - with pytest.raises(TypeError) as e: - self.index.upsert([dict1]) - assert "sparse" in str(e.value) - assert key in str(e.value) - - def test_upsert_dataframe(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: MockUpsertDelegate( - UpsertResponse(upserted_count=len(upsert_request.vectors)) - ), - ) - df = pd.DataFrame( - [ - { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - }, - { - "id": "vec2", - "values": self.vals2, - "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, - "metadata": self.md2, - }, - ] - ) - self.index.upsert_from_dataframe(df, namespace="ns") - self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], async_call=True) - - def test_upsert_dataframe_sync(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors) - ), - ) - df = pd.DataFrame( - [ - { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - }, - { - "id": "vec2", - "values": self.vals2, - "sparse_values": {"indices": self.sparse_indices_2, "values": self.sparse_values_2}, - "metadata": self.md2, - }, - ] - ) - self.index.upsert_from_dataframe(df, namespace="ns", use_async_requests=False) - self._assert_called_once([self.expected_vec_md_sparse1, self.expected_vec_md_sparse2], async_call=False) - - def test_upsert_dataframe_negative(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - full_dict1 = { - "id": "vec1", - "values": self.vals1, - "sparse_values": {"indices": self.sparse_indices_1, "values": self.sparse_values_1}, - "metadata": self.md1, - } - full_df = pd.DataFrame([full_dict1]) - - # Not a DF - with pytest.raises(ValueError): - self.index.upsert_from_dataframe([full_dict1]) - with pytest.raises(ValueError): - self.index.upsert_from_dataframe(full_dict1) - - # Missing Cols - df = full_df.copy() - df.drop(columns=["id"], inplace=True) - with pytest.raises(ValueError): - self.index.upsert_from_dataframe(df) - - # Excess cols - df = full_df.copy() - df["animals"] = ["dog"] - with pytest.raises(ValueError): - self.index.upsert_from_dataframe(df) - - df = full_df.copy() - df["metadat"] = df["metadata"] - with pytest.raises(ValueError): - self.index.upsert_from_dataframe(df) - - def test_upsert_async_upsertInputVectorsAsync(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns", async_req=True) - self._assert_called_once([self.expected_vec_md1, self.expected_vec_md2], async_call=True) - - def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors) - ), - ) - - result = self.index.upsert( - [self.expected_vec_md1, self.expected_vec_md2], namespace="ns", batch_size=1, show_progress=False - ) - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest( - vectors=[Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" - ), - timeout=None, - ) - - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, UpsertRequest(vectors=[self.expected_vec_md2], namespace="ns"), timeout=None - ) - - assert result.upserted_count == 2 - - def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors) - ), - ) - - result = self.index.upsert( - [ - self.expected_vec_md1, - Vector(id="vec2", values=self.vals2, metadata=dict_to_proto_struct(self.md2)), - Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1)), - ], - namespace="ns", - batch_size=2, - ) - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest(vectors=[self.expected_vec_md1, self.expected_vec_md2], namespace="ns"), - timeout=None, - ) - - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest( - vectors=[Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" - ), - timeout=None, - ) - - assert result.upserted_count == 3 - - def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors) - ), - ) - - result = self.index.upsert([self.expected_vec_md1, self.expected_vec_md2], namespace="ns", batch_size=5) - self._assert_called_once( - [self.expected_vec_md1, self.expected_vec_md2], - ) - - assert result.upserted_count == 2 - - def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): - mocker.patch.object( - self.index, - "_wrap_grpc_call", - autospec=True, - side_effect=lambda stub, upsert_request, timeout: UpsertResponse( - upserted_count=len(upsert_request.vectors) - ), - ) - - result = self.index.upsert( - [("vec1", self.vals1, self.md1), ("vec2", self.vals2, self.md2), ("vec3", self.vals1, self.md1)], - namespace="ns", - batch_size=2, - ) - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest(vectors=[self.expected_vec_md1, self.expected_vec_md2], namespace="ns"), - timeout=None, - ) - - self.index._wrap_grpc_call.assert_any_call( - self.index.stub.Upsert, - UpsertRequest( - vectors=[Vector(id="vec3", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], namespace="ns" - ), - timeout=None, - ) - - assert result.upserted_count == 3 - - def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): - with pytest.raises(ValueError, match="batch_size must be a positive integer"): - self.index.upsert( - [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace="ns", - batch_size=0, - ) - - with pytest.raises(ValueError, match="batch_size must be a positive integer"): - self.index.upsert( - [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace="ns", - batch_size=-1, - ) - - def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): - with pytest.raises(ValueError, match="async_req is not supported when batch_size is provided."): - self.index.upsert( - [Vector(id="vec1", values=self.vals1, metadata=dict_to_proto_struct(self.md1))], - namespace="ns", - batch_size=2, - async_req=True, - ) - - # endregion - - # region: query tests - - def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, vector=self.vals1) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest(top_k=10, vector=self.vals1), - timeout=None, - ) - - def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns", timeout=10) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest(top_k=10, vector=self.vals1, filter=dict_to_proto_struct(self.filter1), namespace="ns"), - timeout=10, - ) - - def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, queries=[(self.vals1,), (self.vals2,)]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest( - queries=[QueryVector(values=self.vals1, filter={}), QueryVector(values=self.vals2, filter={})], top_k=10 - ), - timeout=None, - ) - - def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, queries=[(self.vals1, self.filter1), (self.vals2, self.filter2)]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest( - queries=[ - QueryVector(values=self.vals1, filter=dict_to_proto_struct(self.filter1)), - QueryVector(values=self.vals2, filter=dict_to_proto_struct(self.filter2)), - ], - top_k=10, - ), - timeout=None, - ) - - def test_query_byVecId_queryByVecId(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest(top_k=10, id="vec1", include_metadata=True, include_values=False), - timeout=None, - ) - - # endregion - - # region: delete tests - - def test_delete_byIds_deleteByIds(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.delete(ids=["vec1", "vec2"]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Delete, - DeleteRequest(ids=["vec1", "vec2"]), - timeout=None, - ) - - def test_delete_byIdsAsync_deleteByIdsAsync(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.delete(ids=["vec1", "vec2"], async_req=True) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Delete.future, - DeleteRequest(ids=["vec1", "vec2"]), - timeout=None, - ) - - def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.delete(delete_all=True, filter=self.filter1, namespace="ns", timeout=30) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Delete, - DeleteRequest(delete_all=True, filter=dict_to_proto_struct(self.filter1), namespace="ns"), - timeout=30, - ) - - def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.delete(delete_all=True) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Delete, - DeleteRequest(delete_all=True), - timeout=None, - ) - - # endregion - - # region: fetch tests - - def test_fetch_byIds_fetchByIds(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.fetch(["vec1", "vec2"]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Fetch, - FetchRequest(ids=["vec1", "vec2"]), - timeout=None, - ) - - def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.fetch(["vec1", "vec2"], namespace="ns", timeout=30) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Fetch, - FetchRequest(ids=["vec1", "vec2"], namespace="ns"), - timeout=30, - ) - - # endregion - - # region: update tests - - def test_update_byIdAnValues_updateByIdAndValues(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.update(id="vec1", values=self.vals1, namespace="ns", timeout=30) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Update, - UpdateRequest(id="vec1", values=self.vals1, namespace="ns"), - timeout=30, - ) - - def test_update_byIdAnValuesAsync_updateByIdAndValuesAsync(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.update(id="vec1", values=self.vals1, namespace="ns", timeout=30, async_req=True) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Update.future, - UpdateRequest(id="vec1", values=self.vals1, namespace="ns"), - timeout=30, - ) - - def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.update("vec1", values=self.vals1, set_metadata=self.md1) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Update, - UpdateRequest(id="vec1", values=self.vals1, set_metadata=dict_to_proto_struct(self.md1)), - timeout=None, - ) - - # endregion - - # region: describe index tests - - def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.describe_index_stats() - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.DescribeIndexStats, - DescribeIndexStatsRequest(), - timeout=None, - ) - - def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.describe_index_stats(filter=self.filter1) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.DescribeIndexStats, - DescribeIndexStatsRequest(filter=dict_to_proto_struct(self.filter1)), - timeout=None, - ) - - # endregion - - -class MockUpsertDelegate: - def __init__(self, upsert_response: UpsertResponse): - self.response = upsert_response - - def result(self, timeout): - return self.response diff --git a/tests/unit_grpc/test_grpc_index_describe_index_stats.py b/tests/unit_grpc/test_grpc_index_describe_index_stats.py new file mode 100644 index 000000000..fc779e9f0 --- /dev/null +++ b/tests/unit_grpc/test_grpc_index_describe_index_stats.py @@ -0,0 +1,37 @@ +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from pinecone import Config +from pinecone.grpc import GRPCIndex +from pinecone import DescribeIndexStatsRequest +from pinecone.core.grpc.protos.vector_service_pb2 import ( + DescribeIndexStatsRequest, +) +from pinecone.grpc.utils import dict_to_proto_struct + + +class TestGrpcIndexDescribeIndexStats: + def setup_method(self): + self.config = Config(api_key="test-api-key", host="foo") + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") + + def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.describe_index_stats() + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.DescribeIndexStats, + DescribeIndexStatsRequest(), + timeout=None, + ) + + def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker, filter1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.describe_index_stats(filter=filter1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.DescribeIndexStats, + DescribeIndexStatsRequest(filter=dict_to_proto_struct(filter1)), + timeout=None, + ) diff --git a/tests/unit_grpc/test_grpc_index_fetch.py b/tests/unit_grpc/test_grpc_index_fetch.py new file mode 100644 index 000000000..1c750c4cb --- /dev/null +++ b/tests/unit_grpc/test_grpc_index_fetch.py @@ -0,0 +1,35 @@ +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from pinecone import Config +from pinecone.grpc import GRPCIndex +from pinecone.core.grpc.protos.vector_service_pb2 import ( + FetchRequest, +) + + +class TestGrpcIndexFetch: + def setup_method(self): + self.config = Config(api_key="test-api-key", host="foo") + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") + + def test_fetch_byIds_fetchByIds(self, mocker): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.fetch(["vec1", "vec2"]) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Fetch, + FetchRequest(ids=["vec1", "vec2"]), + timeout=None, + ) + + def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.fetch(["vec1", "vec2"], namespace="ns", timeout=30) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Fetch, + FetchRequest(ids=["vec1", "vec2"], namespace="ns"), + timeout=30, + ) diff --git a/tests/unit_grpc/test_grpc_index_query.py b/tests/unit_grpc/test_grpc_index_query.py new file mode 100644 index 000000000..153f3cb30 --- /dev/null +++ b/tests/unit_grpc/test_grpc_index_query.py @@ -0,0 +1,72 @@ +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from pinecone import Config +from pinecone.grpc import GRPCIndex +from pinecone.core.grpc.protos.vector_service_pb2 import ( + QueryRequest, + QueryVector, +) +from pinecone.grpc.utils import dict_to_proto_struct + + +class TestGrpcIndexQuery: + def setup_method(self): + self.config = Config(api_key="test-api-key", host="foo") + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") + + def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker, vals1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, vector=vals1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, vector=vals1), + timeout=None, + ) + + def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker, vals1, filter1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, vector=vals1, filter=filter1, namespace="ns", timeout=10) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, vector=vals1, filter=dict_to_proto_struct(filter1), namespace="ns"), + timeout=10, + ) + + def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker, vals1, vals2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, queries=[(vals1,), (vals2,)]) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest( + queries=[QueryVector(values=vals1, filter={}), QueryVector(values=vals2, filter={})], top_k=10 + ), + timeout=None, + ) + + def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker, vals1, vals2, filter1, filter2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, queries=[(vals1, filter1), (vals2, filter2)]) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest( + queries=[ + QueryVector(values=vals1, filter=dict_to_proto_struct(filter1)), + QueryVector(values=vals2, filter=dict_to_proto_struct(filter2)), + ], + top_k=10, + ), + timeout=None, + ) + + def test_query_byVecId_queryByVecId(self, mocker): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, id="vec1", include_metadata=True, include_values=False), + timeout=None, + ) diff --git a/tests/unit_grpc/test_grpc_index_update.py b/tests/unit_grpc/test_grpc_index_update.py new file mode 100644 index 000000000..ce07c4969 --- /dev/null +++ b/tests/unit_grpc/test_grpc_index_update.py @@ -0,0 +1,45 @@ +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from pinecone import Config +from pinecone.grpc import GRPCIndex +from pinecone.core.grpc.protos.vector_service_pb2 import ( + UpdateRequest, +) +from pinecone.grpc.utils import dict_to_proto_struct + + +class TestGrpcIndexUpdate: + def setup_method(self): + self.config = Config(api_key="test-api-key", host="foo") + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") + + def test_update_byIdAnValues_updateByIdAndValues(self, mocker, vals1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update(id="vec1", values=vals1, namespace="ns", timeout=30) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update, + UpdateRequest(id="vec1", values=vals1, namespace="ns"), + timeout=30, + ) + + def test_update_byIdAnValuesAsync_updateByIdAndValuesAsync(self, mocker, vals1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update(id="vec1", values=vals1, namespace="ns", timeout=30, async_req=True) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update.future, + UpdateRequest(id="vec1", values=vals1, namespace="ns"), + timeout=30, + ) + + def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker, vals1, md1): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.update("vec1", values=vals1, set_metadata=md1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update, + UpdateRequest(id="vec1", values=vals1, set_metadata=dict_to_proto_struct(md1)), + timeout=None, + ) diff --git a/tests/unit_grpc/test_grpc_index_upsert.py b/tests/unit_grpc/test_grpc_index_upsert.py new file mode 100644 index 000000000..a7d4ff7ae --- /dev/null +++ b/tests/unit_grpc/test_grpc_index_upsert.py @@ -0,0 +1,580 @@ +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from pinecone import Config +from pinecone.grpc import GRPCIndex +from pinecone.core.grpc.protos.vector_service_pb2 import ( + Vector, + UpsertRequest, + UpsertResponse, + SparseValues, +) +from pinecone.grpc.utils import dict_to_proto_struct + + +class MockUpsertDelegate: + def __init__(self, upsert_response: UpsertResponse): + self.response = upsert_response + + def result(self, timeout): + return self.response + + +@pytest.fixture +def expected_vec1(vals1): + return Vector(id="vec1", values=vals1, metadata={}) + + +@pytest.fixture +def expected_vec2(vals2): + return Vector(id="vec2", values=vals2, metadata={}) + + +@pytest.fixture +def expected_vec_md1(vals1, md1): + return Vector(id="vec1", values=vals1, metadata=dict_to_proto_struct(md1)) + + +@pytest.fixture +def expected_vec_md2(vals2, md2): + return Vector(id="vec2", values=vals2, metadata=dict_to_proto_struct(md2)) + + +@pytest.fixture +def expected_vec_md_sparse1(vals1, md1, sparse_indices_1, sparse_values_1): + return Vector( + id="vec1", + values=vals1, + metadata=dict_to_proto_struct(md1), + sparse_values=SparseValues(indices=sparse_indices_1, values=sparse_values_1), + ) + + +@pytest.fixture +def expected_vec_md_sparse2(vals2, md2, sparse_indices_2, sparse_values_2): + return Vector( + id="vec2", + values=vals2, + metadata=dict_to_proto_struct(md2), + sparse_values=SparseValues(indices=sparse_indices_2, values=sparse_values_2), + ) + + +class TestGrpcIndexUpsert: + def setup_method(self): + self.config = Config(api_key="test-api-key", host="foo") + self.index = GRPCIndex(config=self.config, index_name="example-name", _endpoint_override="test-endpoint") + + def _assert_called_once(self, vectors, async_call=False): + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert.future if async_call else self.index.stub.Upsert, + UpsertRequest(vectors=vectors, namespace="ns"), + timeout=None, + ) + + def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker, vals1, vals2, expected_vec1, expected_vec2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([("vec1", vals1), ("vec2", vals2)], namespace="ns") + self._assert_called_once([expected_vec1, expected_vec2]) + + def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD( + self, mocker, vals1, md1, vals2, md2, expected_vec_md1, expected_vec_md2 + ): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([("vec1", vals1, md1), ("vec2", vals2, md2)], namespace="ns") + self._assert_called_once( + [expected_vec_md1, expected_vec_md2], + ) + + def test_upsert_vectors_upsertInputVectors(self, mocker, expected_vec_md1, expected_vec_md2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([expected_vec_md1, expected_vec_md2], namespace="ns") + self._assert_called_once( + [expected_vec_md1, expected_vec_md2], + ) + + def test_upsert_vectors_upsertInputVectorsSparse( + self, + mocker, + vals1, + md1, + vals2, + md2, + sparse_indices_1, + sparse_values_1, + sparse_indices_2, + sparse_values_2, + expected_vec_md_sparse1, + expected_vec_md_sparse2, + ): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert( + [ + Vector( + id="vec1", + values=vals1, + metadata=dict_to_proto_struct(md1), + sparse_values=SparseValues(indices=sparse_indices_1, values=sparse_values_1), + ), + Vector( + id="vec2", + values=vals2, + metadata=dict_to_proto_struct(md2), + sparse_values=SparseValues(indices=sparse_indices_2, values=sparse_values_2), + ), + ], + namespace="ns", + ) + self._assert_called_once([expected_vec_md_sparse1, expected_vec_md_sparse2]) + + def test_upsert_dict(self, mocker, vals1, vals2, expected_vec1, expected_vec2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = {"id": "vec1", "values": vals1} + dict2 = {"id": "vec2", "values": vals2} + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once([expected_vec1, expected_vec2]) + + def test_upsert_dict_md(self, mocker, vals1, md1, vals2, md2, expected_vec_md1, expected_vec_md2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = {"id": "vec1", "values": vals1, "metadata": md1} + dict2 = {"id": "vec2", "values": vals2, "metadata": md2} + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once([expected_vec_md1, expected_vec_md2]) + + def test_upsert_dict_sparse( + self, mocker, vals1, vals2, sparse_indices_1, sparse_values_1, sparse_indices_2, sparse_values_2 + ): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + } + dict2 = { + "id": "vec2", + "values": vals2, + "sparse_values": {"indices": sparse_indices_2, "values": sparse_values_2}, + } + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once( + [ + Vector( + id="vec1", + values=vals1, + metadata={}, + sparse_values=SparseValues(indices=sparse_indices_1, values=sparse_values_1), + ), + Vector( + id="vec2", + values=vals2, + metadata={}, + sparse_values=SparseValues(indices=sparse_indices_2, values=sparse_values_2), + ), + ] + ) + + def test_upsert_dict_sparse_md( + self, mocker, vals1, md1, vals2, md2, sparse_indices_1, sparse_values_1, sparse_indices_2, sparse_values_2 + ): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + dict1 = { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + "metadata": md1, + } + dict2 = { + "id": "vec2", + "values": vals2, + "sparse_values": {"indices": sparse_indices_2, "values": sparse_values_2}, + "metadata": md2, + } + self.index.upsert([dict1, dict2], namespace="ns") + self._assert_called_once( + [ + Vector( + id="vec1", + values=vals1, + metadata=dict_to_proto_struct(md1), + sparse_values=SparseValues(indices=sparse_indices_1, values=sparse_values_1), + ), + Vector( + id="vec2", + values=vals2, + metadata=dict_to_proto_struct(md2), + sparse_values=SparseValues(indices=sparse_indices_2, values=sparse_values_2), + ), + ] + ) + + def test_upsert_dict_negative(self, mocker, vals1, vals2, md2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + + # Missing required keys + dict1 = {"values": vals1} + dict2 = {"id": "vec2"} + with pytest.raises(ValueError): + self.index.upsert([dict1, dict2]) + with pytest.raises(ValueError): + self.index.upsert([dict1]) + with pytest.raises(ValueError): + self.index.upsert([dict2]) + + # Excess keys + dict1 = {"id": "vec1", "values": vals1} + dict2 = {"id": "vec2", "values": vals2, "animal": "dog"} + with pytest.raises(ValueError) as e: + self.index.upsert([dict1, dict2]) + assert "animal" in str(e.value) + + dict1 = {"id": "vec1", "values": vals1, "metadatta": md2} + dict2 = {"id": "vec2", "values": vals2} + with pytest.raises(ValueError) as e: + self.index.upsert([dict1, dict2]) + assert "metadatta" in str(e.value) + + @pytest.mark.parametrize( + "key,new_val", + [ + ("values", ["the", "lazy", "fox"]), + ("values", "the lazy fox"), + ("values", 0.5), + ("metadata", np.nan), + ("metadata", ["key1", "key2"]), + ("sparse_values", "cat"), + ("sparse_values", []), + ], + ) + def test_upsert_dict_with_invalid_values(self, mocker, key, new_val, vals1, md1, sparse_indices_1, sparse_values_1): + mocker.patch.object(self.index, "_wrap_grpc_call", 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(TypeError) as e: + self.index.upsert([dict1]) + assert key 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): + mocker.patch.object(self.index, "_wrap_grpc_call", 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(TypeError) as e: + self.index.upsert([dict1]) + assert str(new_val) in str(e.value) + + @pytest.mark.parametrize( + "key,new_val", + [ + ("indices", 3), + ("indices", [1.2, 0.5]), + ("values", ["1", "4.4"]), + ("values", 0.5), + ], + ) + def test_upsert_dict_with_invalid_sparse_values( + self, mocker, key, new_val, vals1, md1, sparse_indices_1, sparse_values_1 + ): + mocker.patch.object(self.index, "_wrap_grpc_call", 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["sparse_values"][key] = new_val + with pytest.raises(TypeError) as e: + self.index.upsert([dict1]) + assert "sparse" in str(e.value) + assert key in str(e.value) + + def test_upsert_dataframe( + self, + mocker, + vals1, + sparse_indices_1, + sparse_values_1, + md1, + vals2, + sparse_indices_2, + sparse_values_2, + md2, + expected_vec_md_sparse1, + expected_vec_md_sparse2, + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: MockUpsertDelegate( + UpsertResponse(upserted_count=len(upsert_request.vectors)) + ), + ) + df = pd.DataFrame( + [ + { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + "metadata": md1, + }, + { + "id": "vec2", + "values": vals2, + "sparse_values": {"indices": sparse_indices_2, "values": sparse_values_2}, + "metadata": md2, + }, + ] + ) + self.index.upsert_from_dataframe(df, namespace="ns") + self._assert_called_once([expected_vec_md_sparse1, expected_vec_md_sparse2], async_call=True) + + def test_upsert_dataframe_sync( + self, + mocker, + vals1, + md1, + vals2, + md2, + sparse_indices_1, + sparse_values_1, + sparse_indices_2, + sparse_values_2, + expected_vec_md_sparse1, + expected_vec_md_sparse2, + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + df = pd.DataFrame( + [ + { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + "metadata": md1, + }, + { + "id": "vec2", + "values": vals2, + "sparse_values": {"indices": sparse_indices_2, "values": sparse_values_2}, + "metadata": md2, + }, + ] + ) + self.index.upsert_from_dataframe(df, namespace="ns", use_async_requests=False) + self._assert_called_once([expected_vec_md_sparse1, expected_vec_md_sparse2], async_call=False) + + def test_upsert_dataframe_negative( + self, mocker, vals1, md1, vals2, md2, sparse_indices_1, sparse_values_1, sparse_indices_2, sparse_values_2 + ): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + full_dict1 = { + "id": "vec1", + "values": vals1, + "sparse_values": {"indices": sparse_indices_1, "values": sparse_values_1}, + "metadata": md1, + } + full_df = pd.DataFrame([full_dict1]) + + # Not a DF + with pytest.raises(ValueError): + self.index.upsert_from_dataframe([full_dict1]) + with pytest.raises(ValueError): + self.index.upsert_from_dataframe(full_dict1) + + # Missing Cols + df = full_df.copy() + df.drop(columns=["id"], inplace=True) + with pytest.raises(ValueError): + self.index.upsert_from_dataframe(df) + + # Excess cols + df = full_df.copy() + df["animals"] = ["dog"] + with pytest.raises(ValueError): + self.index.upsert_from_dataframe(df) + + df = full_df.copy() + df["metadat"] = df["metadata"] + with pytest.raises(ValueError): + self.index.upsert_from_dataframe(df) + + def test_upsert_async_upsertInputVectorsAsync(self, mocker, expected_vec_md1, expected_vec_md2): + mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) + self.index.upsert([expected_vec_md1, expected_vec_md2], namespace="ns", async_req=True) + self._assert_called_once([expected_vec_md1, expected_vec_md2], async_call=True) + + def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches( + self, mocker, vals1, md1, expected_vec_md1, expected_vec_md2 + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [expected_vec_md1, expected_vec_md2], namespace="ns", batch_size=1, show_progress=False + ) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id="vec1", values=vals1, metadata=dict_to_proto_struct(md1))], namespace="ns" + ), + timeout=None, + ) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, UpsertRequest(vectors=[expected_vec_md2], namespace="ns"), timeout=None + ) + + assert result.upserted_count == 2 + + def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches( + self, mocker, vals1, vals2, md1, md2, expected_vec_md1, expected_vec_md2 + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [ + expected_vec_md1, + Vector(id="vec2", values=vals2, metadata=dict_to_proto_struct(md2)), + Vector(id="vec3", values=vals1, metadata=dict_to_proto_struct(md1)), + ], + namespace="ns", + batch_size=2, + ) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest(vectors=[expected_vec_md1, expected_vec_md2], namespace="ns"), + timeout=None, + ) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id="vec3", values=vals1, metadata=dict_to_proto_struct(md1))], namespace="ns" + ), + timeout=None, + ) + + assert result.upserted_count == 3 + + def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches( + self, mocker, expected_vec_md1, expected_vec_md2 + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert([expected_vec_md1, expected_vec_md2], namespace="ns", batch_size=5) + self._assert_called_once( + [expected_vec_md1, expected_vec_md2], + ) + + assert result.upserted_count == 2 + + def test_upsert_tuplesList_vectorsUpsertedInBatches( + self, mocker, vals1, md1, vals2, md2, expected_vec_md1, expected_vec_md2 + ): + mocker.patch.object( + self.index, + "_wrap_grpc_call", + autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors) + ), + ) + + result = self.index.upsert( + [("vec1", vals1, md1), ("vec2", vals2, md2), ("vec3", vals1, md1)], + namespace="ns", + batch_size=2, + ) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest(vectors=[expected_vec_md1, expected_vec_md2], namespace="ns"), + timeout=None, + ) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id="vec3", values=vals1, metadata=dict_to_proto_struct(md1))], namespace="ns" + ), + timeout=None, + ) + + assert result.upserted_count == 3 + + def test_upsert_batchSizeIsNotPositive_errorIsRaised(self, vals1, md1): + with pytest.raises(ValueError, match="batch_size must be a positive integer"): + self.index.upsert( + [Vector(id="vec1", values=vals1, metadata=dict_to_proto_struct(md1))], + namespace="ns", + batch_size=0, + ) + + with pytest.raises(ValueError, match="batch_size must be a positive integer"): + self.index.upsert( + [Vector(id="vec1", values=vals1, metadata=dict_to_proto_struct(md1))], + namespace="ns", + batch_size=-1, + ) + + def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self, vals1, md1): + with pytest.raises(ValueError, match="async_req is not supported when batch_size is provided."): + self.index.upsert( + [Vector(id="vec1", values=vals1, metadata=dict_to_proto_struct(md1))], + namespace="ns", + batch_size=2, + async_req=True, + ) diff --git a/tests/unit_grpc/test_vector_factory_grpc.py b/tests/unit_grpc/test_vector_factory_grpc.py new file mode 100644 index 000000000..491f1c398 --- /dev/null +++ b/tests/unit_grpc/test_vector_factory_grpc.py @@ -0,0 +1,294 @@ +import numpy as np +import pandas as pd +import pytest + +from pinecone.grpc.vector_factory_grpc import VectorFactoryGRPC +from pinecone.grpc import Vector, SparseValues +from pinecone.grpc.utils import dict_to_proto_struct +from pinecone import Vector as NonGRPCVector, SparseValues as NonGRPCSparseValues + + +class TestVectorFactory: + def test_build_when_returns_vector_unmodified(self): + vec = Vector(id="1", values=[0.1, 0.2, 0.3]) + assert VectorFactoryGRPC.build(vec) == vec + assert VectorFactoryGRPC.build(vec).__class__ == Vector + + def test_build_when_nongrpc_vector(self): + vec = NonGRPCVector(id="1", values=[0.1, 0.2, 0.3]) + assert VectorFactoryGRPC.build(vec) == Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + + def test_build_when_nongrpc_vector_with_metadata(self): + vec = NonGRPCVector(id="1", values=[0.1, 0.2, 0.3], metadata={"genre": "comedy"}) + assert VectorFactoryGRPC.build(vec) == Vector( + 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(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]), + ) + + def test_build_when_tuple_with_two_values(self): + tup = ("1", [0.1, 0.2, 0.3]) + actual = VectorFactoryGRPC.build(tup) + expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata={}) + assert actual == expected + + def test_build_when_tuple_with_three_values(self): + tup = ("1", [0.1, 0.2, 0.3], {"genre": "comedy"}) + actual = VectorFactoryGRPC.build(tup) + expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"})) + assert actual == expected + + def test_build_when_tuple_with_numpy_array(self): + tup = ("1", np.array([0.1, 0.2, 0.3]), {"genre": "comedy"}) + actual = VectorFactoryGRPC.build(tup) + expected = Vector(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_when_tuple_with_pandas_array(self): + tup = ("1", pd.array([0.1, 0.2, 0.3])) + actual = VectorFactoryGRPC.build(tup) + expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + 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"): + tup = ("1", [0.1, 0.2, 0.3], {"a": "b"}, "extra") + VectorFactoryGRPC.build(tup) + + def test_build_when_tuple_too_short(self): + with pytest.raises(ValueError, match="Found a tuple of length 1 which is not supported"): + 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} + actual = VectorFactoryGRPC.build(d) + expected = Vector(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]} + actual = VectorFactoryGRPC.build(d) + expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({})) + assert actual == expected + + def test_build_when_dict_with_sparse_values_dict(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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("sv_klass", [SparseValues, NonGRPCSparseValues]) + def test_build_with_dict_with_sparse_values_object(self, sv_klass): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": sv_klass(indices=[0, 2], values=[0.1, 0.3]), + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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("metadata", [{"genre": "comedy"}, dict_to_proto_struct({"genre": "comedy"})]) + def test_build_when_dict_with_numpy_values(self, metadata): + d = {"id": "1", "values": np.array([0.1, 0.2, 0.3]), "metadata": metadata} + actual = VectorFactoryGRPC.build(d) + expected = Vector(id="1", values=[0.1, 0.2, 0.3], metadata=dict_to_proto_struct({"genre": "comedy"})) + assert actual == expected + + @pytest.mark.parametrize("metadata", [{"genre": "comedy"}, dict_to_proto_struct({"genre": "comedy"})]) + def test_build_when_dict_with_pandas_values(self, metadata): + d = {"id": "1", "values": pd.array([0.1, 0.2, 0.3]), "metadata": metadata} + actual = VectorFactoryGRPC.build(d) + expected = Vector(id="1", 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) + + def test_build_when_dict_sparse_values(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2], "values": [0.1, 0.3]}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_dict_sparse_values_when_SparseValues(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": SparseValues(indices=[0, 2], values=[0.1, 0.3]), + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_dict_sparse_values_errors_when_not_dict(self): + with pytest.raises(ValueError, match="Column `sparse_values` is expected to be a dictionary"): + d = {"id": "1", "values": [0.1, 0.2, 0.3], "metadata": {"genre": "comedy"}, "sparse_values": "not a dict"} + VectorFactoryGRPC.build(d) + + def test_build_when_dict_sparse_values_errors_when_missing_indices(self): + with pytest.raises(ValueError, match="Missing required keys in data in column `sparse_values`"): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"values": [0.1, 0.3]}, + } + VectorFactoryGRPC.build(d) + + def test_build_when_dict_sparse_values_errors_when_missing_values(self): + with pytest.raises(ValueError, match="Missing required keys in data in column `sparse_values`"): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2]}, + } + VectorFactoryGRPC.build(d) + + def test_build_when_dict_sparse_values_errors_when_indices_not_list(self): + with pytest.raises(ValueError, match="Found unexpected data in column `sparse_values`"): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": "not a list", "values": [0.1, 0.3]}, + } + VectorFactoryGRPC.build(d) + + def test_build_when_dict_sparse_values_errors_when_values_not_list(self): + with pytest.raises(ValueError, match="Found unexpected data in column `sparse_values`"): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2], "values": "not a list"}, + } + VectorFactoryGRPC.build(d) + + def test_build_when_dict_sparse_values_when_values_is_ndarray(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2], "values": np.array([0.1, 0.3])}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_dict_sparse_values_when_indices_is_pandas_IntegerArray(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": pd.array([0, 2]), "values": [0.1, 0.3]}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_dict_sparse_values_when_values_is_pandas_FloatingArray(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": [0, 2], "values": pd.array([0.1, 0.3])}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_dict_sparse_values_when_indices_is_ndarray(self): + d = { + "id": "1", + "values": [0.1, 0.2, 0.3], + "metadata": {"genre": "comedy"}, + "sparse_values": {"indices": np.array([0, 2]), "values": [0.1, 0.3]}, + } + actual = VectorFactoryGRPC.build(d) + expected = Vector( + 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 + + def test_build_when_errors_when_other_type(self): + with pytest.raises(ValueError, match="Invalid vector value passed: cannot interpret type"): + VectorFactoryGRPC.build(1) From 5370b0986ae82186833d937aada6380c8a9fdf9a Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 12 Jan 2024 20:39:41 -0500 Subject: [PATCH 35/39] Add `usage.read_units` in fetch/query responses (#270) ## Problem Need to update the generated core and surface usage data properly. ## Solution - Make a few adjustments related to tag names in updated OpenAPISpec - Update data integration tests to assert `read_units` are present - Make adjustments to GRPC response parsing to account for the new data attributes ## Type of Change - [x] New feature (non-breaking change which adds functionality) --- pinecone/control/index_host_store.py | 2 +- pinecone/control/pinecone.py | 2 +- pinecone/core/client/api/__init__.py | 2 +- ...d_indexes_api.py => manage_indexes_api.py} | 2 +- .../api/manage_serverless_indexes_api.py | 525 ------------------ pinecone/core/client/api_client.py | 2 +- pinecone/core/client/apis/__init__.py | 5 +- pinecone/core/client/model/fetch_response.py | 6 + pinecone/core/client/model/query_response.py | 6 + pinecone/core/client/model/usage.py | 255 +++++++++ pinecone/core/client/models/__init__.py | 1 + .../core/grpc/protos/vector_service_pb2.py | 135 ++++- .../core/grpc/protos/vector_service_pb2.pyi | 41 +- pinecone/grpc/utils.py | 13 +- tests/integration/data/test_fetch.py | 5 + tests/integration/data/test_query.py | 5 +- 16 files changed, 438 insertions(+), 569 deletions(-) rename pinecone/core/client/api/{manage_pod_indexes_api.py => manage_indexes_api.py} (99%) delete mode 100644 pinecone/core/client/api/manage_serverless_indexes_api.py create mode 100644 pinecone/core/client/model/usage.py diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index 7a5622e62..cf2e1df4d 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,6 +1,6 @@ from typing import Dict from pinecone.config import Config -from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi +from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi as IndexOperationsApi from pinecone.core.client.exceptions import PineconeException from pinecone.utils import normalize_host diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 000709607..2099bbef7 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -5,7 +5,7 @@ from pinecone.config import PineconeConfig, Config -from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi as IndexOperationsApi +from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi as IndexOperationsApi from pinecone.core.client.api_client import ApiClient from pinecone.utils import get_user_agent from pinecone.core.client.models import ( diff --git a/pinecone/core/client/api/__init__.py b/pinecone/core/client/api/__init__.py index a4e950c74..97879a3a6 100644 --- a/pinecone/core/client/api/__init__.py +++ b/pinecone/core/client/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.client.apis import ManagePodIndexesApi +# from pinecone.core.client.apis import ManageIndexesApi diff --git a/pinecone/core/client/api/manage_pod_indexes_api.py b/pinecone/core/client/api/manage_indexes_api.py similarity index 99% rename from pinecone/core/client/api/manage_pod_indexes_api.py rename to pinecone/core/client/api/manage_indexes_api.py index 53bd97434..d74f1124a 100644 --- a/pinecone/core/client/api/manage_pod_indexes_api.py +++ b/pinecone/core/client/api/manage_indexes_api.py @@ -31,7 +31,7 @@ from pinecone.core.client.model.index_model import IndexModel -class ManagePodIndexesApi(object): +class ManageIndexesApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech diff --git a/pinecone/core/client/api/manage_serverless_indexes_api.py b/pinecone/core/client/api/manage_serverless_indexes_api.py deleted file mode 100644 index 33eefee7d..000000000 --- a/pinecone/core/client/api/manage_serverless_indexes_api.py +++ /dev/null @@ -1,525 +0,0 @@ -""" - Pineonce.io Public 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: 1.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.client.model_utils import ( # noqa: F401 - check_allowed_values, - check_validations, - date, - datetime, - file_type, - none_type, - validate_and_convert_types -) -from pinecone.core.client.model.create_index_request import CreateIndexRequest -from pinecone.core.client.model.error_response import ErrorResponse -from pinecone.core.client.model.index_list import IndexList -from pinecone.core.client.model.index_model import IndexModel - - -class ManageServerlessIndexesApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def __create_index( - self, - create_index_request, - **kwargs - ): - """create_index # noqa: E501 - - This operation deploys a Pinecone index. This is where you specify the measure of similarity, the dimension of vectors to be stored in the index, which cloud provider you would like to deploy with, and more. # 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(create_index_request, async_req=True) - >>> result = thread.get() - - Args: - create_index_request (CreateIndexRequest): The desired configuration for the index. - - 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_request'] = \ - create_index_request - return self.call_with_http_info(**kwargs) - - self.create_index = _Endpoint( - settings={ - 'response_type': (IndexModel,), - 'auth': [ - 'ApiKeyAuth' - ], - 'endpoint_path': '/indexes', - 'operation_id': 'create_index', - 'http_method': 'POST', - 'servers': [ - { - 'url': "https://api.pinecone.io", - 'description': "No description provided", - }, - ] - }, - params_map={ - 'all': [ - 'create_index_request', - ], - 'required': [ - 'create_index_request', - ], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - 'create_index_request': - (CreateIndexRequest,), - }, - 'attribute_map': { - }, - 'location_map': { - 'create_index_request': 'body', - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [ - 'application/json' - ] - }, - api_client=api_client, - callable=__create_index - ) - - def __delete_index( - self, - index_name, - **kwargs - ): - """delete_index # noqa: E501 - - This operation deletes an existing index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.delete_index(index_name, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index to delete - - 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['index_name'] = \ - index_name - return self.call_with_http_info(**kwargs) - - self.delete_index = _Endpoint( - settings={ - 'response_type': None, - 'auth': [ - 'ApiKeyAuth' - ], - 'endpoint_path': '/indexes/{index_name}', - 'operation_id': 'delete_index', - 'http_method': 'DELETE', - 'servers': [ - { - 'url': "https://api.pinecone.io", - 'description': "No description provided", - }, - ] - }, - params_map={ - 'all': [ - 'index_name', - ], - 'required': [ - 'index_name', - ], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - 'index_name': - (str,), - }, - 'attribute_map': { - 'index_name': 'index_name', - }, - 'location_map': { - 'index_name': 'path', - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [], - }, - api_client=api_client, - callable=__delete_index - ) - - def __describe_index( - self, - index_name, - **kwargs - ): - """describe_index # noqa: E501 - - Get a description of an index. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_index(index_name, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index to be described - - 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['index_name'] = \ - index_name - return self.call_with_http_info(**kwargs) - - self.describe_index = _Endpoint( - settings={ - 'response_type': (IndexModel,), - 'auth': [ - 'ApiKeyAuth' - ], - 'endpoint_path': '/indexes/{index_name}', - 'operation_id': 'describe_index', - 'http_method': 'GET', - 'servers': [ - { - 'url': "https://api.pinecone.io", - 'description': "No description provided", - }, - ] - }, - params_map={ - 'all': [ - 'index_name', - ], - 'required': [ - 'index_name', - ], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - 'index_name': - (str,), - }, - 'attribute_map': { - 'index_name': 'index_name', - }, - 'location_map': { - 'index_name': 'path', - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [], - }, - api_client=api_client, - callable=__describe_index - ) - - def __list_indexes( - self, - **kwargs - ): - """list_indexes # noqa: E501 - - This operation returns a list of your Pinecone indexes. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_indexes(async_req=True) - >>> result = thread.get() - - - 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: - IndexList - 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') - return self.call_with_http_info(**kwargs) - - self.list_indexes = _Endpoint( - settings={ - 'response_type': (IndexList,), - 'auth': [ - 'ApiKeyAuth' - ], - 'endpoint_path': '/indexes', - 'operation_id': 'list_indexes', - 'http_method': 'GET', - 'servers': [ - { - 'url': "https://api.pinecone.io", - 'description': "No description provided", - }, - ] - }, - params_map={ - 'all': [ - ], - 'required': [], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - }, - 'attribute_map': { - }, - 'location_map': { - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [], - }, - api_client=api_client, - callable=__list_indexes - ) diff --git a/pinecone/core/client/api_client.py b/pinecone/core/client/api_client.py index e7e2feae5..de64b8aed 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/client/api_client.py @@ -761,7 +761,7 @@ def __call__(self, *args, **kwargs): """ This method is invoked when endpoints are called Example: - api_instance = ManagePodIndexesApi() + api_instance = ManageIndexesApi() api_instance.configure_index # this is an instance of the class Endpoint api_instance.configure_index() # this invokes api_instance.configure_index.__call__() which then invokes the callable functions stored in that endpoint at diff --git a/pinecone/core/client/apis/__init__.py b/pinecone/core/client/apis/__init__.py index bc39a4d40..11b2ed348 100644 --- a/pinecone/core/client/apis/__init__.py +++ b/pinecone/core/client/apis/__init__.py @@ -6,7 +6,7 @@ # raise a `RecursionError`. # In order to avoid this, import only the API that you directly need like: # -# from .api.manage_pod_indexes_api import ManagePodIndexesApi +# from .api.manage_indexes_api import ManageIndexesApi # # or import this package, but before doing it, use: # @@ -14,6 +14,5 @@ # sys.setrecursionlimit(n) # Import APIs into API package: -from pinecone.core.client.api.manage_pod_indexes_api import ManagePodIndexesApi -from pinecone.core.client.api.manage_serverless_indexes_api import ManageServerlessIndexesApi +from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi from pinecone.core.client.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/client/model/fetch_response.py b/pinecone/core/client/model/fetch_response.py index a142ed42c..632596a9d 100644 --- a/pinecone/core/client/model/fetch_response.py +++ b/pinecone/core/client/model/fetch_response.py @@ -30,7 +30,9 @@ def lazy_import(): + from pinecone.core.client.model.usage import Usage from pinecone.core.client.model.vector import Vector + globals()['Usage'] = Usage globals()['Vector'] = Vector @@ -89,6 +91,7 @@ def openapi_types(): return { 'vectors': ({str: (Vector,)},), # noqa: E501 'namespace': (str,), # noqa: E501 + 'usage': (Usage,), # noqa: E501 } @cached_property @@ -99,6 +102,7 @@ def discriminator(): attribute_map = { 'vectors': 'vectors', # noqa: E501 'namespace': 'namespace', # noqa: E501 + 'usage': 'usage', # noqa: E501 } read_only_vars = { @@ -144,6 +148,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) vectors ({str: (Vector,)}): [optional] # noqa: E501 namespace (str): The namespace of the vectors.. [optional] # noqa: E501 + usage (Usage): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -227,6 +232,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) vectors ({str: (Vector,)}): [optional] # noqa: E501 namespace (str): The namespace of the vectors.. [optional] # noqa: E501 + usage (Usage): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/query_response.py b/pinecone/core/client/model/query_response.py index 5f932cc43..a81724e12 100644 --- a/pinecone/core/client/model/query_response.py +++ b/pinecone/core/client/model/query_response.py @@ -32,8 +32,10 @@ def lazy_import(): from pinecone.core.client.model.scored_vector import ScoredVector from pinecone.core.client.model.single_query_results import SingleQueryResults + from pinecone.core.client.model.usage import Usage globals()['ScoredVector'] = ScoredVector globals()['SingleQueryResults'] = SingleQueryResults + globals()['Usage'] = Usage class QueryResponse(ModelNormal): @@ -92,6 +94,7 @@ def openapi_types(): 'results': ([SingleQueryResults],), # noqa: E501 'matches': ([ScoredVector],), # noqa: E501 'namespace': (str,), # noqa: E501 + 'usage': (Usage,), # noqa: E501 } @cached_property @@ -103,6 +106,7 @@ def discriminator(): 'results': 'results', # noqa: E501 'matches': 'matches', # noqa: E501 'namespace': 'namespace', # noqa: E501 + 'usage': 'usage', # noqa: E501 } read_only_vars = { @@ -149,6 +153,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 namespace (str): The namespace for the vectors.. [optional] # noqa: E501 + usage (Usage): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -233,6 +238,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 results ([SingleQueryResults]): DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.. [optional] # noqa: E501 matches ([ScoredVector]): The matches for the vectors.. [optional] # noqa: E501 namespace (str): The namespace for the vectors.. [optional] # noqa: E501 + usage (Usage): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/pinecone/core/client/model/usage.py b/pinecone/core/client/model/usage.py new file mode 100644 index 000000000..c38b88d25 --- /dev/null +++ b/pinecone/core/client/model/usage.py @@ -0,0 +1,255 @@ +""" + Pineonce.io Public 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: 1.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.client.exceptions import PineconeApiAttributeError + + + +class Usage(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, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'read_units': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'read_units': 'readUnits', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Usage - 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,) + read_units (int): The number of read 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__,) + + 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 + """Usage - 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,) + read_units (int): The number of read 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__,) + + 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/client/models/__init__.py b/pinecone/core/client/models/__init__.py index 11efdc9de..d15a24e8b 100644 --- a/pinecone/core/client/models/__init__.py +++ b/pinecone/core/client/models/__init__.py @@ -44,4 +44,5 @@ from pinecone.core.client.model.update_request import UpdateRequest from pinecone.core.client.model.upsert_request import UpsertRequest from pinecone.core.client.model.upsert_response import UpsertResponse +from pinecone.core.client.model.usage import Usage from pinecone.core.client.model.vector import Vector diff --git a/pinecone/core/grpc/protos/vector_service_pb2.py b/pinecone/core/grpc/protos/vector_service_pb2.py index 665ead6c7..2bd90fadf 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.py +++ b/pinecone/core/grpc/protos/vector_service_pb2.py @@ -23,7 +23,7 @@ syntax='proto3', serialized_options=b'\n\021io.pinecone.protoP\001Z/github.com/pinecone-io/new-go-pinecone/pinecone\222A\366\002\022K\n\014Pinecone API\";\n\017Pinecone.io Ops\022\023https://pinecone.io\032\023support@pinecone.io\0329{index_name}-{project_name}.svc.{environment}.pinecone.io*\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', create_key=_descriptor._internal_create_key, - serialized_pb=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\"~\n\x0cSparseValues\x12\x35\n\x07indices\x18\x01 \x03(\rB$\x92\x41\x1eJ\x16[1, 312, 822, 14, 980]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12\x37\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\xe0\x41\x02\"\xfd\x01\n\x06Vector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\x02\x12G\n\x06values\x18\x02 \x03(\x02\x42\x37\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\xe0\x41\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}\"\x93\x02\n\x0cScoredVector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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}\"d\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x0c\x92\x41\x06x\xe8\x07\x80\x01\x01\xe0\x41\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\"h\n\x0c\x46\x65tchRequest\x12+\n\x03ids\x18\x01 \x03(\tB\x1e\x92\x41\x18J\x10[\"id-0\", \"id-1\"]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12+\n\tnamespace\x18\x02 \x01(\tB\x18\x92\x41\x15J\x13\"example-namespace\"\"\xa3\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\"\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\"\xd0\x02\n\x0bQueryVector\x12G\n\x06values\x18\x01 \x03(\x02\x42\x37\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\xe0\x41\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}}\"\xfa\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\x1c\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\xe0\x41\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\"\"l\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\"\xb2\x02\n\rUpdateRequest\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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\xbd\x05\n\rVectorService\x12\x63\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/upsert:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06upsert\x12v\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"K\x82\xd3\xe4\x93\x02\'\"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x92\x41\x1b\n\x11Vector Operations*\x06\x64\x65lete\x12[\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse\"3\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x92\x41\x1a\n\x11Vector Operations*\x05\x66\x65tch\x12V\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse\".\x82\xd3\xe4\x93\x02\x0b\"\x06/query:\x01*\x92\x41\x1a\n\x11Vector Operations*\x05query\x12\x63\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/update:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06update\x12\xb4\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse\"e\x82\xd3\xe4\x93\x02\x33\"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_stats\x92\x41)\n\x11Vector Operations*\x14\x64\x65scribe_index_statsB\xc0\x03\n\x11io.pinecone.protoP\x01Z/github.com/pinecone-io/new-go-pinecone/pinecone\x92\x41\xf6\x02\x12K\n\x0cPinecone API\";\n\x0fPinecone.io Ops\x12\x13https://pinecone.io\x1a\x13support@pinecone.io\x1a\x39{index_name}-{project_name}.svc.{environment}.pinecone.io*\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' + serialized_pb=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\"~\n\x0cSparseValues\x12\x35\n\x07indices\x18\x01 \x03(\rB$\x92\x41\x1eJ\x16[1, 312, 822, 14, 980]x\xe8\x07\x80\x01\x01\xe0\x41\x02\x12\x37\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\xe0\x41\x02\"\xfd\x01\n\x06Vector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\x02\x12G\n\x06values\x18\x02 \x03(\x02\x42\x37\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\xe0\x41\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}\"\x93\x02\n\x0cScoredVector\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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}\"d\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x0c\x92\x41\x06x\xe8\x07\x80\x01\x01\xe0\x41\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\"h\n\x0c\x46\x65tchRequest\x12+\n\x03ids\x18\x01 \x03(\tB\x1e\x92\x41\x18J\x10[\"id-0\", \"id-1\"]x\xe8\x07\x80\x01\x01\xe0\x41\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\"\xd0\x02\n\x0bQueryVector\x12G\n\x06values\x18\x01 \x03(\x02\x42\x37\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\xe0\x41\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}}\"\xfa\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\x1c\x92\x41\x16J\x02\x31\x30Y\x00\x00\x00\x00\x00\x88\xc3@i\x00\x00\x00\x00\x00\x00\xf0?\xe0\x41\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\"G\n\x05Usage\x12/\n\nread_units\x18\x01 \x01(\rB\x16\x92\x41\x13J\x11{\"read_units\": 5}H\x00\x88\x01\x01\x42\r\n\x0b_read_units\"\xb2\x02\n\rUpdateRequest\x12,\n\x02id\x18\x01 \x01(\tB \x92\x41\x1aJ\x12\"example-vector-1\"x\x80\x04\x80\x01\x01\xe0\x41\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\xbd\x05\n\rVectorService\x12\x63\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/upsert:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06upsert\x12v\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"K\x82\xd3\xe4\x93\x02\'\"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x92\x41\x1b\n\x11Vector Operations*\x06\x64\x65lete\x12[\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse\"3\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x92\x41\x1a\n\x11Vector Operations*\x05\x66\x65tch\x12V\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse\".\x82\xd3\xe4\x93\x02\x0b\"\x06/query:\x01*\x92\x41\x1a\n\x11Vector Operations*\x05query\x12\x63\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse\"8\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/update:\x01*\x92\x41\x1b\n\x11Vector Operations*\x06update\x12\xb4\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse\"e\x82\xd3\xe4\x93\x02\x33\"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_stats\x92\x41)\n\x11Vector Operations*\x14\x64\x65scribe_index_statsB\xc0\x03\n\x11io.pinecone.protoP\x01Z/github.com/pinecone-io/new-go-pinecone/pinecone\x92\x41\xf6\x02\x12K\n\x0cPinecone API\";\n\x0fPinecone.io Ops\x12\x13https://pinecone.io\x1a\x13support@pinecone.io\x1a\x39{index_name}-{project_name}.svc.{environment}.pinecone.io*\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' , dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_api_dot_field__behavior__pb2.DESCRIPTOR,protoc__gen__openapiv2_dot_options_dot_annotations__pb2.DESCRIPTOR,]) @@ -404,8 +404,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=1398, - serialized_end=1453, + serialized_start=1450, + serialized_end=1505, ) _FETCHRESPONSE = _descriptor.Descriptor( @@ -430,6 +430,13 @@ message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=b'\222A\025J\023\"example-namespace\"', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='usage', full_name='FetchResponse.usage', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\023J\021{\"read_units\": 5}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -441,9 +448,14 @@ syntax='proto3', extension_ranges=[], oneofs=[ + _descriptor.OneofDescriptor( + name='_usage', full_name='FetchResponse._usage', + index=0, containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[]), ], serialized_start=1290, - serialized_end=1453, + serialized_end=1515, ) @@ -502,8 +514,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=1456, - serialized_end=1792, + serialized_start=1518, + serialized_end=1854, ) @@ -590,8 +602,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=1795, - serialized_end=2301, + serialized_start=1857, + serialized_end=2363, ) @@ -629,8 +641,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2303, - serialized_end=2400, + serialized_start=2365, + serialized_end=2462, ) @@ -663,6 +675,13 @@ message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='usage', full_name='QueryResponse.usage', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\023J\021{\"read_units\": 5}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -674,9 +693,51 @@ syntax='proto3', extension_ranges=[], oneofs=[ + _descriptor.OneofDescriptor( + name='_usage', full_name='QueryResponse._usage', + index=0, containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[]), + ], + serialized_start=2465, + serialized_end=2635, +) + + +_USAGE = _descriptor.Descriptor( + name='Usage', + full_name='Usage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='read_units', full_name='Usage.read_units', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\222A\023J\021{\"read_units\": 5}', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ ], - serialized_start=2402, - serialized_end=2510, + serialized_options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='_read_units', full_name='Usage._read_units', + index=0, containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[]), + ], + serialized_start=2637, + serialized_end=2708, ) @@ -735,8 +796,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2513, - serialized_end=2819, + serialized_start=2711, + serialized_end=3017, ) @@ -760,8 +821,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2821, - serialized_end=2837, + serialized_start=3019, + serialized_end=3035, ) @@ -792,8 +853,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2839, - serialized_end=2907, + serialized_start=3037, + serialized_end=3105, ) @@ -824,8 +885,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2909, - serialized_end=2961, + serialized_start=3107, + serialized_end=3159, ) @@ -863,8 +924,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=3163, - serialized_end=3231, + serialized_start=3361, + serialized_end=3429, ) _DESCRIBEINDEXSTATSRESPONSE = _descriptor.Descriptor( @@ -915,8 +976,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=2964, - serialized_end=3374, + serialized_start=3162, + serialized_end=3572, ) _VECTOR.fields_by_name['sparse_values'].message_type = _SPARSEVALUES @@ -928,6 +989,10 @@ _FETCHRESPONSE_VECTORSENTRY.fields_by_name['value'].message_type = _VECTOR _FETCHRESPONSE_VECTORSENTRY.containing_type = _FETCHRESPONSE _FETCHRESPONSE.fields_by_name['vectors'].message_type = _FETCHRESPONSE_VECTORSENTRY +_FETCHRESPONSE.fields_by_name['usage'].message_type = _USAGE +_FETCHRESPONSE.oneofs_by_name['_usage'].fields.append( + _FETCHRESPONSE.fields_by_name['usage']) +_FETCHRESPONSE.fields_by_name['usage'].containing_oneof = _FETCHRESPONSE.oneofs_by_name['_usage'] _QUERYVECTOR.fields_by_name['sparse_values'].message_type = _SPARSEVALUES _QUERYVECTOR.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT _QUERYREQUEST.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT @@ -936,6 +1001,13 @@ _SINGLEQUERYRESULTS.fields_by_name['matches'].message_type = _SCOREDVECTOR _QUERYRESPONSE.fields_by_name['results'].message_type = _SINGLEQUERYRESULTS _QUERYRESPONSE.fields_by_name['matches'].message_type = _SCOREDVECTOR +_QUERYRESPONSE.fields_by_name['usage'].message_type = _USAGE +_QUERYRESPONSE.oneofs_by_name['_usage'].fields.append( + _QUERYRESPONSE.fields_by_name['usage']) +_QUERYRESPONSE.fields_by_name['usage'].containing_oneof = _QUERYRESPONSE.oneofs_by_name['_usage'] +_USAGE.oneofs_by_name['_read_units'].fields.append( + _USAGE.fields_by_name['read_units']) +_USAGE.fields_by_name['read_units'].containing_oneof = _USAGE.oneofs_by_name['_read_units'] _UPDATEREQUEST.fields_by_name['sparse_values'].message_type = _SPARSEVALUES _UPDATEREQUEST.fields_by_name['set_metadata'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT _DESCRIBEINDEXSTATSREQUEST.fields_by_name['filter'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT @@ -955,6 +1027,7 @@ DESCRIPTOR.message_types_by_name['QueryRequest'] = _QUERYREQUEST DESCRIPTOR.message_types_by_name['SingleQueryResults'] = _SINGLEQUERYRESULTS DESCRIPTOR.message_types_by_name['QueryResponse'] = _QUERYRESPONSE +DESCRIPTOR.message_types_by_name['Usage'] = _USAGE DESCRIPTOR.message_types_by_name['UpdateRequest'] = _UPDATEREQUEST DESCRIPTOR.message_types_by_name['UpdateResponse'] = _UPDATERESPONSE DESCRIPTOR.message_types_by_name['DescribeIndexStatsRequest'] = _DESCRIBEINDEXSTATSREQUEST @@ -1061,6 +1134,13 @@ }) _sym_db.RegisterMessage(QueryResponse) +Usage = _reflection.GeneratedProtocolMessageType('Usage', (_message.Message,), { + 'DESCRIPTOR' : _USAGE, + '__module__' : 'vector_service_pb2' + # @@protoc_insertion_point(class_scope:Usage) + }) +_sym_db.RegisterMessage(Usage) + UpdateRequest = _reflection.GeneratedProtocolMessageType('UpdateRequest', (_message.Message,), { 'DESCRIPTOR' : _UPDATEREQUEST, '__module__' : 'vector_service_pb2' @@ -1125,6 +1205,7 @@ _FETCHREQUEST.fields_by_name['namespace']._options = None _FETCHRESPONSE_VECTORSENTRY._options = None _FETCHRESPONSE.fields_by_name['namespace']._options = None +_FETCHRESPONSE.fields_by_name['usage']._options = None _QUERYVECTOR.fields_by_name['values']._options = None _QUERYVECTOR.fields_by_name['top_k']._options = None _QUERYVECTOR.fields_by_name['namespace']._options = None @@ -1139,6 +1220,8 @@ _QUERYREQUEST.fields_by_name['id']._options = None _SINGLEQUERYRESULTS.fields_by_name['namespace']._options = None _QUERYRESPONSE.fields_by_name['results']._options = None +_QUERYRESPONSE.fields_by_name['usage']._options = None +_USAGE.fields_by_name['read_units']._options = None _UPDATEREQUEST.fields_by_name['id']._options = None _UPDATEREQUEST.fields_by_name['values']._options = None _UPDATEREQUEST.fields_by_name['set_metadata']._options = None @@ -1157,8 +1240,8 @@ index=0, serialized_options=None, create_key=_descriptor._internal_create_key, - serialized_start=3377, - serialized_end=4078, + serialized_start=3575, + serialized_end=4276, methods=[ _descriptor.MethodDescriptor( name='Upsert', diff --git a/pinecone/core/grpc/protos/vector_service_pb2.pyi b/pinecone/core/grpc/protos/vector_service_pb2.pyi index 0c2c73f62..bbbae21e3 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.pyi +++ b/pinecone/core/grpc/protos/vector_service_pb2.pyi @@ -1,11 +1,14 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" from google.protobuf.descriptor import ( Descriptor as google___protobuf___descriptor___Descriptor, FileDescriptor as google___protobuf___descriptor___FileDescriptor, ) from google.protobuf.internal.containers import ( + MessageMap as google___protobuf___internal___containers___MessageMap, RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer, ) @@ -21,7 +24,6 @@ from google.protobuf.struct_pb2 import ( from typing import ( Iterable as typing___Iterable, Mapping as typing___Mapping, - MutableMapping as typing___MutableMapping, Optional as typing___Optional, Text as typing___Text, ) @@ -185,14 +187,20 @@ class FetchResponse(google___protobuf___message___Message): namespace: typing___Text = ... @property - def vectors(self) -> typing___MutableMapping[typing___Text, type___Vector]: ... + def vectors(self) -> google___protobuf___internal___containers___MessageMap[typing___Text, type___Vector]: ... + + @property + def usage(self) -> type___Usage: ... def __init__(self, *, vectors : typing___Optional[typing___Mapping[typing___Text, type___Vector]] = None, namespace : typing___Optional[typing___Text] = None, + usage : typing___Optional[type___Usage] = None, ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal[u"namespace",b"namespace",u"vectors",b"vectors"]) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"_usage",b"_usage",u"usage",b"usage"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"_usage",b"_usage",u"namespace",b"namespace",u"usage",b"usage",u"vectors",b"vectors"]) -> None: ... + def WhichOneof(self, oneof_group: typing_extensions___Literal[u"_usage",b"_usage"]) -> typing_extensions___Literal["usage"]: ... type___FetchResponse = FetchResponse class QueryVector(google___protobuf___message___Message): @@ -278,15 +286,34 @@ class QueryResponse(google___protobuf___message___Message): @property def matches(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___ScoredVector]: ... + @property + def usage(self) -> type___Usage: ... + def __init__(self, *, results : typing___Optional[typing___Iterable[type___SingleQueryResults]] = None, matches : typing___Optional[typing___Iterable[type___ScoredVector]] = None, namespace : typing___Optional[typing___Text] = None, + usage : typing___Optional[type___Usage] = None, ) -> None: ... - def ClearField(self, field_name: typing_extensions___Literal[u"matches",b"matches",u"namespace",b"namespace",u"results",b"results"]) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"_usage",b"_usage",u"usage",b"usage"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"_usage",b"_usage",u"matches",b"matches",u"namespace",b"namespace",u"results",b"results",u"usage",b"usage"]) -> None: ... + def WhichOneof(self, oneof_group: typing_extensions___Literal[u"_usage",b"_usage"]) -> typing_extensions___Literal["usage"]: ... type___QueryResponse = QueryResponse +class Usage(google___protobuf___message___Message): + DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... + read_units: builtin___int = ... + + def __init__(self, + *, + read_units : typing___Optional[builtin___int] = None, + ) -> None: ... + def HasField(self, field_name: typing_extensions___Literal[u"_read_units",b"_read_units",u"read_units",b"read_units"]) -> builtin___bool: ... + def ClearField(self, field_name: typing_extensions___Literal[u"_read_units",b"_read_units",u"read_units",b"read_units"]) -> None: ... + def WhichOneof(self, oneof_group: typing_extensions___Literal[u"_read_units",b"_read_units"]) -> typing_extensions___Literal["read_units"]: ... +type___Usage = Usage + class UpdateRequest(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... id: typing___Text = ... @@ -366,7 +393,7 @@ class DescribeIndexStatsResponse(google___protobuf___message___Message): total_vector_count: builtin___int = ... @property - def namespaces(self) -> typing___MutableMapping[typing___Text, type___NamespaceSummary]: ... + def namespaces(self) -> google___protobuf___internal___containers___MessageMap[typing___Text, type___NamespaceSummary]: ... def __init__(self, *, diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index 6ca64f3db..f23d70fce 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -4,6 +4,7 @@ from pinecone.core.client.models import ( Vector as _Vector, + Usage, ScoredVector, SparseValues, FetchResponse, @@ -20,6 +21,7 @@ class QueryResponseKwargs(NamedTuple): namespace: Optional[str] matches: Optional[list] results: Optional[list] + usage: Usage def _generate_request_id() -> str: return str(uuid.uuid4()) @@ -52,13 +54,19 @@ def parse_fetch_response(response: dict): metadata=vec.get("metadata", None), _check_type=False, ) + + usage = parse_usage(response) return FetchResponse( vectors=vd, namespace=namespace, + usage=usage, _check_type=False ) +def parse_usage(response): + u = response.get("usage", {}) + return Usage(read_units=int(u.get("readUnits", 0))) def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): @@ -101,7 +109,10 @@ def parse_query_response(response: dict, unary_query: bool, _check_type: bool = matches = [] results = res - kw = QueryResponseKwargs(_check_type, namespace, matches, results) + usage = parse_usage(response) + + + kw = QueryResponseKwargs(_check_type, namespace, matches, results, usage) kw_dict = kw._asdict() kw_dict["_check_type"] = kw.check_type return QueryResponse(**kw._asdict()) diff --git a/tests/integration/data/test_fetch.py b/tests/integration/data/test_fetch.py index feef6b5f5..7151be557 100644 --- a/tests/integration/data/test_fetch.py +++ b/tests/integration/data/test_fetch.py @@ -16,6 +16,11 @@ def test_fetch_multiple_by_id( results = idx.fetch(ids=['1', '2', '4'], namespace=target_namespace) assert isinstance(results, FetchResponse) == True + + assert results.usage != None + assert results.usage['read_units'] != None + assert results.usage['read_units'] > 0 + assert results.namespace == target_namespace assert len(results.vectors) == 3 assert results.vectors['1'].id == '1' diff --git a/tests/integration/data/test_query.py b/tests/integration/data/test_query.py index 45a83a695..e1c7ba88e 100644 --- a/tests/integration/data/test_query.py +++ b/tests/integration/data/test_query.py @@ -18,8 +18,9 @@ def test_query_by_id(self, idx, namespace, use_nondefault_namespace): assert isinstance(results, QueryResponse) == True assert results.namespace == target_namespace - # TODO fix usage - # assert results.usage != None + assert results.usage != None + assert results.usage['read_units'] != None + assert results.usage['read_units'] > 0 # By default, does not include values or metadata record_with_metadata = find_by_id(results.matches, '4') From d86dd1b2dd4bb665347bcdf6f7611ec5b557ec2a Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 12 Jan 2024 21:42:30 -0500 Subject: [PATCH 36/39] Remove deprecated `queries` option in `query()` (#272) ## Problem There was an argument on the `query()` method for passing multiple queries at once. This has long been deprecated in the API and SDK, so it's time to remove it. ## Solution - Clean up the `queries` option to both `Index#query` and `IndexGRPC#query`. - Remove code no longer needed to interpret the many forms these query options could take - Cleanup and simplify response parsing logic - Remove related tests passing `queries` kwarg ## Type of Change - [x] Breaking change (fix or feature that would cause existing functionality to not work as expected) ## Test Plan Recently added integration test suite gives high confidence queries still work after this change. --- pinecone/data/index.py | 41 +++------------ pinecone/grpc/__init__.py | 2 - pinecone/grpc/index_grpc.py | 25 ++------- pinecone/grpc/utils.py | 66 +++++------------------- pinecone/grpc/vector_factory_grpc.py | 1 - tests/unit/test_index.py | 22 -------- tests/unit_grpc/test_grpc_index_query.py | 28 ---------- 7 files changed, 24 insertions(+), 161 deletions(-) diff --git a/pinecone/data/index.py b/pinecone/data/index.py index a9f7b80f2..2feee0117 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -11,7 +11,6 @@ FetchResponse, QueryRequest, QueryResponse, - QueryVector, RpcStatus, ScoredVector, SingleQueryResults, @@ -33,7 +32,6 @@ "FetchResponse", "QueryRequest", "QueryResponse", - "QueryVector", "RpcStatus", "ScoredVector", "SingleQueryResults", @@ -60,12 +58,8 @@ "async_req", ) -def parse_query_response(response: QueryResponse, unary_query: bool): - if unary_query: - response._data_store.pop("results", None) - else: - response._data_store.pop("matches", None) - response._data_store.pop("namespace", None) +def parse_query_response(response: QueryResponse): + response._data_store.pop("results", None) return response class Index(): @@ -324,7 +318,6 @@ def query( top_k: int, vector: Optional[List[float]] = None, id: Optional[str] = None, - queries: Optional[Union[List[QueryVector], List[Tuple]]] = None, namespace: Optional[str] = None, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, @@ -351,13 +344,10 @@ def query( Args: vector (List[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 - `queries`, `id` or `vector`.. [optional] + `id` or `vector`.. [optional] id (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`.. [optional] - queries ([QueryVector]): DEPRECATED. The query vectors. - Each `query()` request can contain only one of the parameters - `queries`, `vector`, or `id`.. [optional] + `vector` or `id`. [optional] top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] @@ -371,35 +361,19 @@ def query( sparse_vector: (Union[SparseValues, Dict[str, Union[List[float], List[int]]]]): sparse values of the query vector. 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. - Keyword Args: - Supports OpenAPI client keyword arguments. See pinecone.core.client.models.QueryRequest for more details. - + Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, and namespace name. """ - def _query_transform(item): - if isinstance(item, QueryVector): - return item - if isinstance(item, tuple): - values, filter = fix_tuple_length(item, 2) - if filter is None: - return QueryVector(values=values, _check_type=_check_type) - else: - return QueryVector(values=values, filter=filter, _check_type=_check_type) - if isinstance(item, Iterable): - return QueryVector(values=item, _check_type=_check_type) - raise ValueError(f"Invalid query vector value passed: cannot interpret type {type(item)}") - _check_type = kwargs.pop("_check_type", False) - queries = list(map(_query_transform, queries)) if queries is not None else None sparse_vector = self._parse_sparse_values_arg(sparse_vector) args_dict = self._parse_non_empty_args( [ ("vector", vector), ("id", id), - ("queries", queries), + ("queries", None), ("top_k", top_k), ("namespace", namespace), ("filter", filter), @@ -416,8 +390,7 @@ def _query_transform(item): ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}, ) - unary_query = True if vector is not None or id else False - return parse_query_response(response, unary_query) + return parse_query_response(response) @validate_and_convert_errors def update( diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py index 71efa350a..c6505a363 100644 --- a/pinecone/grpc/__init__.py +++ b/pinecone/grpc/__init__.py @@ -3,9 +3,7 @@ from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector as GRPCVector, - QueryVector as GRPCQueryVector, SparseValues as GRPCSparseValues, Vector, - QueryVector, SparseValues ) \ No newline at end of file diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index e52dc9686..e70511ee1 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -1,7 +1,5 @@ import logging -import numbers -from typing import Optional, Dict, Iterable, Union, List, Tuple, Any, TypedDict, cast -from collections.abc import Mapping +from typing import Optional, Dict, Union, List, Tuple, Any, TypedDict, cast from google.protobuf import json_format @@ -31,7 +29,6 @@ ) from pinecone import Vector as NonGRPCVector from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub -from pinecone.utils import fix_tuple_length from .base import GRPCIndexBase from .future import PineconeGrpcFuture @@ -293,7 +290,6 @@ def query( self, vector: Optional[List[float]] = None, id: Optional[str] = None, - queries: Optional[Union[List[GRPCQueryVector], List[Tuple]]] = None, namespace: Optional[str] = None, top_k: Optional[int] = None, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, @@ -323,9 +319,6 @@ def query( id (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`.. [optional] - queries ([GRPCQueryVector]): DEPRECATED. The query vectors. - Each `query()` request can contain only one of the parameters - `queries`, `vector`, or `id`.. [optional] top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] @@ -344,18 +337,7 @@ def query( and namespace name. """ - def _query_transform(item): - if isinstance(item, GRPCQueryVector): - return item - if isinstance(item, tuple): - values, filter = fix_tuple_length(item, 2) - filter = dict_to_proto_struct(filter) - return GRPCQueryVector(values=values, filter=filter) - if isinstance(item, Iterable): - return GRPCQueryVector(values=item) - raise ValueError(f"Invalid query vector value passed: cannot interpret type {type(item)}") - - queries = list(map(_query_transform, queries)) if queries is not None else None + queries = None if filter is not None: filter_struct = dict_to_proto_struct(filter) @@ -382,8 +364,7 @@ def _query_transform(item): timeout = kwargs.pop("timeout", None) response = self._wrap_grpc_call(self.stub.Query, request, timeout=timeout) json_response = json_format.MessageToDict(response) - unary_query = True if vector is not None or id else False - return parse_query_response(json_response, unary_query, _check_type=False) + return parse_query_response(json_response, _check_type=False) def update( self, diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index f23d70fce..c1f69bbbf 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -2,29 +2,21 @@ from google.protobuf.struct_pb2 import Struct +def _generate_request_id() -> str: + return str(uuid.uuid4()) + from pinecone.core.client.models import ( Vector as _Vector, Usage, ScoredVector, SparseValues, FetchResponse, - SingleQueryResults, QueryResponse, DescribeIndexStatsResponse, NamespaceSummary, ) -from typing import NamedTuple, Optional - -class QueryResponseKwargs(NamedTuple): - check_type: bool - namespace: Optional[str] - matches: Optional[list] - results: Optional[list] - usage: Usage - -def _generate_request_id() -> str: - return str(uuid.uuid4()) +from typing import Optional def dict_to_proto_struct(d: Optional[dict]) -> "Struct": if not d: @@ -54,13 +46,11 @@ def parse_fetch_response(response: dict): metadata=vec.get("metadata", None), _check_type=False, ) - - usage = parse_usage(response) return FetchResponse( vectors=vd, namespace=namespace, - usage=usage, + usage=parse_usage(response), _check_type=False ) @@ -69,26 +59,8 @@ def parse_usage(response): return Usage(read_units=int(u.get("readUnits", 0))) -def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): - res = [] - - # TODO: consider deleting this deprecated case - for match in response.get("results", []): - namespace = match.get("namespace", "") - m = [] - if "matches" in match: - for item in match["matches"]: - sc = ScoredVector( - id=item["id"], - score=item.get("score", 0.0), - values=item.get("values", []), - sparse_values=parse_sparse_values(item.get("sparseValues")), - metadata=item.get("metadata", None), - ) - m.append(sc) - res.append(SingleQueryResults(matches=m, namespace=namespace)) - - m = [] +def parse_query_response(response: dict, _check_type: bool = False): + matches = [] for item in response.get("matches", []): sc = ScoredVector( id=item["id"], @@ -98,24 +70,14 @@ def parse_query_response(response: dict, unary_query: bool, _check_type: bool = metadata=item.get("metadata", None), _check_type=_check_type, ) - m.append(sc) - - if unary_query: - namespace = response.get("namespace", "") - matches = m - results = [] - else: - namespace = "" - matches = [] - results = res + matches.append(sc) - usage = parse_usage(response) - - - kw = QueryResponseKwargs(_check_type, namespace, matches, results, usage) - kw_dict = kw._asdict() - kw_dict["_check_type"] = kw.check_type - return QueryResponse(**kw._asdict()) + return QueryResponse( + namespace=response.get("namespace", ""), + matches=matches, + usage = parse_usage(response), + _check_type=_check_type + ) def parse_stats_response(response: dict): diff --git a/pinecone/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py index c1ff3c097..c5368d731 100644 --- a/pinecone/grpc/vector_factory_grpc.py +++ b/pinecone/grpc/vector_factory_grpc.py @@ -20,7 +20,6 @@ from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector as GRPCVector, - QueryVector as GRPCQueryVector, SparseValues as GRPCSparseValues, ) from pinecone import ( diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 468222b44..ce451674e 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -363,28 +363,6 @@ def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): pinecone.QueryRequest(top_k=10, vector=self.vals1, filter=self.filter1, namespace="ns") ) - def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): - mocker.patch.object(self.index._vector_api, "query", autospec=True) - self.index.query(top_k=10, queries=[(self.vals1,), (self.vals2,)]) - self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest( - top_k=10, queries=[pinecone.QueryVector(values=self.vals1), pinecone.QueryVector(values=self.vals2)] - ) - ) - - def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): - mocker.patch.object(self.index._vector_api, "query", autospec=True) - self.index.query(top_k=10, queries=[(self.vals1, self.filter1), (self.vals2, self.filter2)]) - self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest( - top_k=10, - queries=[ - pinecone.QueryVector(values=self.vals1, filter=self.filter1), - pinecone.QueryVector(values=self.vals2, filter=self.filter2), - ], - ) - ) - def test_query_byVecId_queryByVecId(self, mocker): mocker.patch.object(self.index._vector_api, "query", autospec=True) self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) diff --git a/tests/unit_grpc/test_grpc_index_query.py b/tests/unit_grpc/test_grpc_index_query.py index 153f3cb30..be44eb564 100644 --- a/tests/unit_grpc/test_grpc_index_query.py +++ b/tests/unit_grpc/test_grpc_index_query.py @@ -8,11 +8,9 @@ from pinecone.grpc import GRPCIndex from pinecone.core.grpc.protos.vector_service_pb2 import ( QueryRequest, - QueryVector, ) from pinecone.grpc.utils import dict_to_proto_struct - class TestGrpcIndexQuery: def setup_method(self): self.config = Config(api_key="test-api-key", host="foo") @@ -36,32 +34,6 @@ def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker, vals1, fil timeout=10, ) - def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker, vals1, vals2): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, queries=[(vals1,), (vals2,)]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest( - queries=[QueryVector(values=vals1, filter={}), QueryVector(values=vals2, filter={})], top_k=10 - ), - timeout=None, - ) - - def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker, vals1, vals2, filter1, filter2): - mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) - self.index.query(top_k=10, queries=[(vals1, filter1), (vals2, filter2)]) - self.index._wrap_grpc_call.assert_called_once_with( - self.index.stub.Query, - QueryRequest( - queries=[ - QueryVector(values=vals1, filter=dict_to_proto_struct(filter1)), - QueryVector(values=vals2, filter=dict_to_proto_struct(filter2)), - ], - top_k=10, - ), - timeout=None, - ) - def test_query_byVecId_queryByVecId(self, mocker): mocker.patch.object(self.index, "_wrap_grpc_call", autospec=True) self.index.query(top_k=10, id="vec1", include_metadata=True, include_values=False) From d0a38b5a0a9f72af1b5287dc62166e69d6622f90 Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 12 Jan 2024 22:07:48 -0500 Subject: [PATCH 37/39] Suppress TqdmExperimentalWarning (#273) ## Problem When loading our library in notebook settings, tqdm (progress bar widget) throws off an annoying warning even though it works fine. It's not a good look. Screenshot 2024-01-12 at 9 51 39 PM ## Solution Suppress the warning using the `warnings` standard library. --- pinecone/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 6f7341b69..a44e710ac 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -1,6 +1,11 @@ """ .. include:: ../README.md """ +import warnings +from tqdm import TqdmExperimentalWarning + +warnings.filterwarnings("ignore", category=TqdmExperimentalWarning) + from .config import * from .exceptions import * from .control import * From 3f2a324bd1d3cbb00b671614a693087b4b6e2d6b Mon Sep 17 00:00:00 2001 From: Jennifer Hamon Date: Fri, 12 Jan 2024 22:36:16 -0500 Subject: [PATCH 38/39] Script for generating load on a test index (#271) ## Problem Need to create some activity to verify billing systems working as expected ## Solution ```shell poetry install --extras grpc PINECONE_API_KEY='key' INDEX_NAME='usage-demo' ITERATIONS=10 CLOUD='aws' REGION='us-west-2' poetry run python3 scripts/generate_usage.py ``` --- scripts/generate_usage.py | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100755 scripts/generate_usage.py diff --git a/scripts/generate_usage.py b/scripts/generate_usage.py new file mode 100755 index 000000000..1a2fc4a36 --- /dev/null +++ b/scripts/generate_usage.py @@ -0,0 +1,90 @@ +import os +import random +import string +from pinecone.grpc import PineconeGRPC + +def read_env_var(name): + value = os.environ.get(name) + if value is None: + raise Exception('Environment variable {} is not set'.format(name)) + return value + +def random_string(length): + return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) + +def random_embedding_values(dimension=2): + return [random.random() for _ in range(dimension)] + +def write_gh_output(name, value): + with open(os.environ['GITHUB_OUTPUT'], 'a') as fh: + print(f'{name}={value}', file=fh) + +DIMENSION = 1536 # common for openai embeddings + +def create_index_if_not_exists(pc, index_name): + if index_name not in pc.list_indexes().names(): + print(f'Index {index_name} does not exist, creating it') + pc.create_index( + name=index_name, + metric='cosine', + dimension=DIMENSION, + spec={ + 'serverless': { + 'cloud': read_env_var('CLOUD'), + 'region': read_env_var('REGION'), + } + } + ) + +upserted_ids = set() + +def main(): + pc = PineconeGRPC(api_key=read_env_var('PINECONE_API_KEY')) + index_name = read_env_var('INDEX_NAME') + iterations = int(read_env_var('ITERATIONS')) + + create_index_if_not_exists(pc, index_name) + + index = pc.Index(name=index_name) + for i in range(iterations): + try: + # Upsert some vectors + items_to_upsert = random.randint(1, 100) + vector_list = [ + { + 'id': random_string(10), + 'values': random_embedding_values(DIMENSION), + 'metadata': { + 'genre': random.choice(['action', 'comedy', 'drama']), + 'runtime': random.randint(60, 120) + } + } for x in range(items_to_upsert) + ] + index.upsert(vectors=vector_list) + print('Upserted {} vectors'.format(items_to_upsert)) + + for v in vector_list: + upserted_ids.add(v['id']) + + # Fetch some vectors + ids_to_fetch = random.sample(upserted_ids, k=random.randint(1, 20)) + print('Fetching {} vectors'.format(len(ids_to_fetch))) + fetched_vectors = index.fetch(ids=ids_to_fetch) + + # Query some vectors + print('Querying 10 times') + for i in range(10): + # Query by vector values + query_vector = random_embedding_values(DIMENSION) + query_results = index.query(vector=query_vector, top_k=10) + + # Delete some vectors + print('Deleting some vectors') + id_to_delete = random.sample(upserted_ids, k=random.randint(1, 10)) + index.delete(ids=id_to_delete) + except Exception as e: + print('Exception: {}'.format(e)) + +if __name__ == '__main__': + main() + From 5a28523cd3f4e0a04a61c9c206559a1df92a7f39 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Sat, 13 Jan 2024 13:08:43 -0500 Subject: [PATCH 39/39] Initial steps on migration testing --- .../actions/create-index-legacy/action.yml | 49 +++++++++++++++ .github/workflows/migration-paths.yaml | 47 ++++++++++++++ scripts/create-index-legacy.py | 63 +++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 .github/actions/create-index-legacy/action.yml create mode 100644 .github/workflows/migration-paths.yaml create mode 100644 scripts/create-index-legacy.py diff --git a/.github/actions/create-index-legacy/action.yml b/.github/actions/create-index-legacy/action.yml new file mode 100644 index 000000000..2b99094f9 --- /dev/null +++ b/.github/actions/create-index-legacy/action.yml @@ -0,0 +1,49 @@ +name: 'Create Index (Legacy / Regional Control Plane)' +description: 'Creates an index to be used in other tests' + +inputs: + pinecone_client_version: + description: 'The version of the Pinecone client to use' + required: false + default: '2.2.4' + index_name: + description: 'The name of the index' + required: true + dimension: + description: 'The dimension of the index' + required: false + default: '1536' + metric: + description: 'The metric of the index' + required: false + default: 'cosine' + PINECONE_ENVIRONMENT: + description: 'The environment of the index' + required: true + PINECONE_API_KEY: + description: 'The Pinecone API key' + required: true + +runs: + using: 'composite' + steps: + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Install pinecone-client + shell: bash + run: | + pip install pinecone-client==${{ inputs.pinecone_client_version }} + + - name: Create index + id: create-index + shell: bash + run: ./python3 scripts/create-index-legacy.py + env: + PINECONE_API_KEY: ${{ inputs.PINECONE_API_KEY }} + PINECONE_ENVIRONMENT: ${{ inputs.PINECONE_ENVIRONMENT }} + INDEX_NAME: ${{ inputs.index_name }} + DIMENSION: ${{ inputs.dimension }} + METRIC: ${{ inputs.metric } diff --git a/.github/workflows/migration-paths.yaml b/.github/workflows/migration-paths.yaml new file mode 100644 index 000000000..34def16d3 --- /dev/null +++ b/.github/workflows/migration-paths.yaml @@ -0,0 +1,47 @@ +name: 'Migration testing' + +on: + workflow_dispatch: {} + + +jobs: + create-index-legacy-paid: + name: Create index + runs-on: ubuntu-latest + strategy: + max-parallel: 1 + matrix: + env: + - asia-southeast1-gcp + # - asia-northeast1-gcp + # - eu-west1-gcp + # - eu-west4-gcp + # - northamerica-northeast1-gcp + # - us-central1-gcp + # - us-east1-gcp + # - us-east4-gcp + # - us-west1-gcp + # - us-west4-gcp + # - eastus-azure + # - us-east-1-aws + + # - gcp-starter + # - asia-southeast1-gcp-free + # - us-west1-gcp-free + # - us-west4-gcp-free + + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Create on legacy control plane + id: create-legacy + uses: ./.github/actions/create-index-legacy + with: + PINECONE_API_KEY: ${{ secrets.V3MIGRATION_API_KEY__ONE_KEY_MANY_ENVS }} + PINECONE_ENVIRONMENT: ${{ matrix.env }} + pinecone_client_version: 2.2.4 + index_name: migration-testing-index + dimension: 1536 + metric: cosine \ No newline at end of file diff --git a/scripts/create-index-legacy.py b/scripts/create-index-legacy.py new file mode 100644 index 000000000..2a98025e7 --- /dev/null +++ b/scripts/create-index-legacy.py @@ -0,0 +1,63 @@ +import random +import string +import os +import pinecone +import time + +def read_env_var(name): + value = os.environ.get(name) + if value is None: + raise Exception('Environment variable {} is not set'.format(name)) + return value + +def random_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)) + +def main(): + api_key = read_env_var('PINECONE_API_KEY') + environment = read_env_var('PINECONE_ENVIRONMENT') + index_name = read_env_var('INDEX_NAME') + dimension = int(read_env_var('DIMENSION')) + metric = read_env_var('METRIC') + + print(f'Beginning test with environment {environment} and index {index_name}') + + pinecone.init( + api_key=api_key, + environment=environment + ) + + if index_name in pinecone.list_indexes(): + print(f'Index {index_name} already exists') + pinecone.delete_index(index_name) + + pinecone.create_index( + name=index_name, + dimension=dimension, + metric=metric + ) + + print(f'Waiting for index {index_name} to be ready...') + time.sleep(60) + print(f'Done waiting.') + + description = pinecone.describe_index(index_name) + print(f'Index description: {description}') + + print(f'Beginning upsert of 1000 vectors to index {index_name}...') + index = pinecone.Index(name=index_name) + for _ in range(100): + vector = random_embedding_values(dimension) + vecs = [{'id': random_string(10), 'values': vector} for i in range(10)] + index.upsert(vectors=[vecs]) + print(f'Done upserting.') + + print(f'Beginning query of index {index_name}...') + index.query(vector=random_embedding_values(dimension)) + print(f'Done querying.') + +if __name__ == '__main__': + main() \ No newline at end of file