From 1981fd8a030efc84072b3d29622264c96801b272 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 13:23:45 -0500 Subject: [PATCH 1/8] Raise exception on load --- .github/workflows/pr.yaml | 42 +- .github/workflows/publish-to-pypi.yaml | 2 +- README.md | 212 +- codegen/apis | 2 +- pinecone/__init__.py | 22 +- pinecone/config/__init__.py | 8 - pinecone/config/config.py | 106 - pinecone/config/openapi.py | 106 - pinecone/config/pinecone_config.py | 37 - pinecone/control/__init__.py | 6 - pinecone/control/index_host_store.py | 53 - pinecone/control/langchain_import_warnings.py | 9 - pinecone/control/pinecone.py | 354 --- pinecone/control/pinecone_asyncio.py | 340 --- pinecone/control/pinecone_interface.py | 792 ------- .../control/pinecone_interface_asyncio.py | 926 -------- pinecone/control/repr_overrides.py | 16 - pinecone/control/request_factory.py | 251 --- pinecone/control/types/__init__.py | 1 - .../types/create_index_for_model_embed.py | 11 - pinecone/core/__init__.py | 0 .../core/grpc/protos/db_data_2025_01_pb2.py | 130 -- .../core/grpc/protos/db_data_2025_01_pb2.pyi | 259 --- .../grpc/protos/db_data_2025_01_pb2_grpc.py | 309 --- pinecone/core/openapi/db_control/__init__.py | 30 - .../core/openapi/db_control/api/__init__.py | 3 - .../db_control/api/manage_indexes_api.py | 1350 ------------ .../core/openapi/db_control/apis/__init__.py | 16 - .../core/openapi/db_control/model/__init__.py | 5 - .../db_control/model/collection_list.py | 268 --- .../db_control/model/collection_model.py | 298 --- .../model/configure_index_request.py | 290 --- .../model/configure_index_request_embed.py | 272 --- .../model/configure_index_request_spec.py | 276 --- .../model/configure_index_request_spec_pod.py | 266 --- .../model/create_collection_request.py | 274 --- .../model/create_index_for_model_request.py | 310 --- .../create_index_for_model_request_embed.py | 286 --- .../db_control/model/create_index_request.py | 309 --- .../db_control/model/deletion_protection.py | 276 --- .../db_control/model/error_response.py | 280 --- .../db_control/model/error_response_error.py | 299 --- .../openapi/db_control/model/index_list.py | 268 --- .../openapi/db_control/model/index_model.py | 335 --- .../db_control/model/index_model_spec.py | 274 --- .../db_control/model/index_model_status.py | 283 --- .../openapi/db_control/model/index_spec.py | 267 --- .../openapi/db_control/model/index_tags.py | 254 --- .../db_control/model/model_index_embed.py | 294 --- .../core/openapi/db_control/model/pod_spec.py | 308 --- .../model/pod_spec_metadata_config.py | 260 --- .../db_control/model/serverless_spec.py | 274 --- .../openapi/db_control/models/__init__.py | 44 - pinecone/core/openapi/db_data/__init__.py | 30 - pinecone/core/openapi/db_data/api/__init__.py | 3 - .../db_data/api/bulk_operations_api.py | 576 ----- .../db_data/api/vector_operations_api.py | 1298 ----------- .../core/openapi/db_data/apis/__init__.py | 17 - .../core/openapi/db_data/model/__init__.py | 5 - .../openapi/db_data/model/delete_request.py | 272 --- .../model/describe_index_stats_request.py | 260 --- .../openapi/db_data/model/fetch_response.py | 278 --- pinecone/core/openapi/db_data/model/hit.py | 278 --- .../db_data/model/import_error_mode.py | 262 --- .../openapi/db_data/model/import_model.py | 299 --- .../db_data/model/index_description.py | 288 --- .../db_data/model/list_imports_response.py | 274 --- .../core/openapi/db_data/model/list_item.py | 260 --- .../openapi/db_data/model/list_response.py | 284 --- .../db_data/model/namespace_summary.py | 260 --- .../core/openapi/db_data/model/pagination.py | 260 --- .../openapi/db_data/model/protobuf_any.py | 264 --- .../db_data/model/protobuf_null_value.py | 276 --- .../openapi/db_data/model/query_request.py | 313 --- .../openapi/db_data/model/query_response.py | 284 --- .../openapi/db_data/model/query_vector.py | 293 --- .../core/openapi/db_data/model/rpc_status.py | 276 --- .../openapi/db_data/model/scored_vector.py | 292 --- .../db_data/model/search_records_request.py | 288 --- .../model/search_records_request_query.py | 290 --- .../model/search_records_request_rerank.py | 284 --- .../db_data/model/search_records_response.py | 284 --- .../model/search_records_response_result.py | 274 --- .../db_data/model/search_records_vector.py | 276 --- .../openapi/db_data/model/search_usage.py | 278 --- .../openapi/db_data/model/search_vector.py | 268 --- .../db_data/model/single_query_results.py | 272 --- .../openapi/db_data/model/sparse_values.py | 275 --- .../db_data/model/start_import_request.py | 285 --- .../db_data/model/start_import_response.py | 262 --- .../openapi/db_data/model/update_request.py | 293 --- .../openapi/db_data/model/upsert_record.py | 266 --- .../openapi/db_data/model/upsert_request.py | 278 --- .../openapi/db_data/model/upsert_response.py | 260 --- pinecone/core/openapi/db_data/model/usage.py | 260 --- pinecone/core/openapi/db_data/model/vector.py | 289 --- .../openapi/db_data/model/vector_values.py | 282 --- .../core/openapi/db_data/models/__init__.py | 57 - pinecone/core/openapi/inference/__init__.py | 30 - .../core/openapi/inference/api/__init__.py | 3 - .../openapi/inference/api/inference_api.py | 308 --- .../core/openapi/inference/apis/__init__.py | 16 - .../core/openapi/inference/model/__init__.py | 5 - .../inference/model/dense_embedding.py | 280 --- .../core/openapi/inference/model/document.py | 254 --- .../openapi/inference/model/embed_request.py | 284 --- .../inference/model/embed_request_inputs.py | 260 --- .../core/openapi/inference/model/embedding.py | 337 --- .../inference/model/embeddings_list.py | 294 --- .../inference/model/embeddings_list_usage.py | 262 --- .../openapi/inference/model/error_response.py | 280 --- .../inference/model/error_response_error.py | 297 --- .../inference/model/ranked_document.py | 284 --- .../openapi/inference/model/rerank_request.py | 302 --- .../openapi/inference/model/rerank_result.py | 288 --- .../inference/model/rerank_result_usage.py | 262 --- .../inference/model/sparse_embedding.py | 292 --- .../openapi/inference/model/vector_type.py | 284 --- .../core/openapi/inference/models/__init__.py | 26 - pinecone/data/__init__.py | 34 - pinecone/data/dataclasses/__init__.py | 6 - pinecone/data/dataclasses/fetch_response.py | 11 - pinecone/data/dataclasses/search_query.py | 59 - .../data/dataclasses/search_query_vector.py | 38 - pinecone/data/dataclasses/search_rerank.py | 61 - pinecone/data/dataclasses/sparse_values.py | 20 - pinecone/data/dataclasses/utils.py | 11 - pinecone/data/dataclasses/vector.py | 41 - pinecone/data/errors.py | 46 - pinecone/data/features/__init__.py | 0 .../data/features/bulk_import/__init__.py | 3 - .../data/features/bulk_import/bulk_import.py | 152 -- .../bulk_import/bulk_import_asyncio.py | 143 -- .../bulk_import_request_factory.py | 67 - pinecone/data/features/inference/__init__.py | 6 - pinecone/data/features/inference/inference.py | 168 -- .../features/inference/inference_asyncio.py | 147 -- .../inference/inference_request_builder.py | 87 - .../features/inference/models/__init__.py | 2 - .../inference/models/embedding_list.py | 29 - .../inference/models/rerank_result.py | 19 - .../data/features/inference/repl_overrides.py | 106 - pinecone/data/import_error.py | 62 - pinecone/data/index.py | 435 ---- pinecone/data/index_asyncio.py | 523 ----- pinecone/data/index_asyncio_interface.py | 807 ------- pinecone/data/interfaces.py | 681 ------ pinecone/data/query_results_aggregator.py | 177 -- pinecone/data/request_factory.py | 271 --- pinecone/data/sparse_values_factory.py | 59 - pinecone/data/types/__init__.py | 8 - pinecone/data/types/query_filter.py | 33 - .../data/types/search_query_typed_dict.py | 36 - .../types/search_query_vector_typed_dict.py | 25 - .../data/types/search_rerank_typed_dict.py | 41 - .../data/types/sparse_vector_typed_dict.py | 6 - pinecone/data/types/vector_metadata_dict.py | 4 - pinecone/data/types/vector_tuple.py | 5 - pinecone/data/types/vector_typed_dict.py | 9 - pinecone/data/vector_factory.py | 109 - pinecone/deprecated_plugins.py | 22 - pinecone/deprecation_warnings.py | 159 -- pinecone/enums/__init__.py | 18 - pinecone/enums/clouds.py | 54 - pinecone/enums/deletion_protection.py | 15 - pinecone/enums/metric.py | 11 - pinecone/enums/pod_index_environment.py | 20 - pinecone/enums/pod_type.py | 20 - pinecone/enums/vector_type.py | 14 - pinecone/exceptions/__init__.py | 29 - pinecone/exceptions/exceptions.py | 14 - pinecone/grpc/__init__.py | 70 - pinecone/grpc/base.py | 95 - pinecone/grpc/channel_factory.py | 101 - pinecone/grpc/config.py | 38 - pinecone/grpc/future.py | 86 - pinecone/grpc/grpc_runner.py | 97 - pinecone/grpc/index_grpc.py | 644 ------ pinecone/grpc/pinecone.py | 136 -- pinecone/grpc/retry.py | 90 - pinecone/grpc/sparse_values_factory.py | 61 - pinecone/grpc/utils.py | 108 - pinecone/grpc/vector_factory_grpc.py | 127 -- pinecone/models/__init__.py | 20 - pinecone/models/collection_description.py | 17 - pinecone/models/collection_list.py | 33 - pinecone/models/index_description.py | 22 - pinecone/models/index_embed.py | 68 - pinecone/models/index_list.py | 32 - pinecone/models/index_model.py | 19 - pinecone/models/list_response.py | 11 - pinecone/models/pod_spec.py | 87 - pinecone/models/serverless_spec.py | 25 - pinecone/openapi_support/__init__.py | 49 - pinecone/openapi_support/api_client.py | 421 ---- pinecone/openapi_support/api_client_utils.py | 203 -- pinecone/openapi_support/api_version.py | 5 - .../openapi_support/asyncio_api_client.py | 363 ---- pinecone/openapi_support/asyncio_endpoint.py | 149 -- pinecone/openapi_support/auth_util.py | 27 - .../openapi_support/cached_class_property.py | 12 - pinecone/openapi_support/configuration.py | 441 ---- pinecone/openapi_support/constants.py | 9 - pinecone/openapi_support/deserializer.py | 58 - pinecone/openapi_support/endpoint.py | 164 -- pinecone/openapi_support/endpoint_utils.py | 185 -- pinecone/openapi_support/exceptions.py | 140 -- pinecone/openapi_support/model_utils.py | 1928 ----------------- pinecone/openapi_support/rest_aiohttp.py | 193 -- pinecone/openapi_support/rest_urllib3.py | 260 --- pinecone/openapi_support/rest_utils.py | 197 -- pinecone/openapi_support/serializer.py | 50 - pinecone/openapi_support/types.py | 14 - pinecone/utils/__init__.py | 39 - pinecone/utils/check_kwargs.py | 12 - pinecone/utils/constants.py | 17 - pinecone/utils/convert_enum_to_string.py | 8 - pinecone/utils/convert_to_list.py | 23 - pinecone/utils/deprecation_notice.py | 6 - pinecone/utils/docslinks.py | 10 - pinecone/utils/error_handling.py | 25 - pinecone/utils/filter_dict.py | 5 - pinecone/utils/fix_tuple_length.py | 3 - pinecone/utils/normalize_host.py | 11 - pinecone/utils/parse_args.py | 5 - pinecone/utils/plugin_aware.py | 27 - pinecone/utils/repr_overrides.py | 15 - pinecone/utils/setup_openapi_client.py | 56 - pinecone/utils/tqdm.py | 28 - pinecone/utils/user_agent.py | 35 - pinecone/utils/version.py | 8 - pyproject.toml | 6 +- 232 files changed, 33 insertions(+), 41218 deletions(-) delete mode 100644 pinecone/config/__init__.py delete mode 100644 pinecone/config/config.py delete mode 100644 pinecone/config/openapi.py delete mode 100644 pinecone/config/pinecone_config.py delete mode 100644 pinecone/control/__init__.py delete mode 100644 pinecone/control/index_host_store.py delete mode 100644 pinecone/control/langchain_import_warnings.py delete mode 100644 pinecone/control/pinecone.py delete mode 100644 pinecone/control/pinecone_asyncio.py delete mode 100644 pinecone/control/pinecone_interface.py delete mode 100644 pinecone/control/pinecone_interface_asyncio.py delete mode 100644 pinecone/control/repr_overrides.py delete mode 100644 pinecone/control/request_factory.py delete mode 100644 pinecone/control/types/__init__.py delete mode 100644 pinecone/control/types/create_index_for_model_embed.py delete mode 100644 pinecone/core/__init__.py delete mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2.py delete mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2.pyi delete mode 100644 pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py delete mode 100644 pinecone/core/openapi/db_control/__init__.py delete mode 100644 pinecone/core/openapi/db_control/api/__init__.py delete mode 100644 pinecone/core/openapi/db_control/api/manage_indexes_api.py delete mode 100644 pinecone/core/openapi/db_control/apis/__init__.py delete mode 100644 pinecone/core/openapi/db_control/model/__init__.py delete mode 100644 pinecone/core/openapi/db_control/model/collection_list.py delete mode 100644 pinecone/core/openapi/db_control/model/collection_model.py delete mode 100644 pinecone/core/openapi/db_control/model/configure_index_request.py delete mode 100644 pinecone/core/openapi/db_control/model/configure_index_request_embed.py delete mode 100644 pinecone/core/openapi/db_control/model/configure_index_request_spec.py delete mode 100644 pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py delete mode 100644 pinecone/core/openapi/db_control/model/create_collection_request.py delete mode 100644 pinecone/core/openapi/db_control/model/create_index_for_model_request.py delete mode 100644 pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py delete mode 100644 pinecone/core/openapi/db_control/model/create_index_request.py delete mode 100644 pinecone/core/openapi/db_control/model/deletion_protection.py delete mode 100644 pinecone/core/openapi/db_control/model/error_response.py delete mode 100644 pinecone/core/openapi/db_control/model/error_response_error.py delete mode 100644 pinecone/core/openapi/db_control/model/index_list.py delete mode 100644 pinecone/core/openapi/db_control/model/index_model.py delete mode 100644 pinecone/core/openapi/db_control/model/index_model_spec.py delete mode 100644 pinecone/core/openapi/db_control/model/index_model_status.py delete mode 100644 pinecone/core/openapi/db_control/model/index_spec.py delete mode 100644 pinecone/core/openapi/db_control/model/index_tags.py delete mode 100644 pinecone/core/openapi/db_control/model/model_index_embed.py delete mode 100644 pinecone/core/openapi/db_control/model/pod_spec.py delete mode 100644 pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py delete mode 100644 pinecone/core/openapi/db_control/model/serverless_spec.py delete mode 100644 pinecone/core/openapi/db_control/models/__init__.py delete mode 100644 pinecone/core/openapi/db_data/__init__.py delete mode 100644 pinecone/core/openapi/db_data/api/__init__.py delete mode 100644 pinecone/core/openapi/db_data/api/bulk_operations_api.py delete mode 100644 pinecone/core/openapi/db_data/api/vector_operations_api.py delete mode 100644 pinecone/core/openapi/db_data/apis/__init__.py delete mode 100644 pinecone/core/openapi/db_data/model/__init__.py delete mode 100644 pinecone/core/openapi/db_data/model/delete_request.py delete mode 100644 pinecone/core/openapi/db_data/model/describe_index_stats_request.py delete mode 100644 pinecone/core/openapi/db_data/model/fetch_response.py delete mode 100644 pinecone/core/openapi/db_data/model/hit.py delete mode 100644 pinecone/core/openapi/db_data/model/import_error_mode.py delete mode 100644 pinecone/core/openapi/db_data/model/import_model.py delete mode 100644 pinecone/core/openapi/db_data/model/index_description.py delete mode 100644 pinecone/core/openapi/db_data/model/list_imports_response.py delete mode 100644 pinecone/core/openapi/db_data/model/list_item.py delete mode 100644 pinecone/core/openapi/db_data/model/list_response.py delete mode 100644 pinecone/core/openapi/db_data/model/namespace_summary.py delete mode 100644 pinecone/core/openapi/db_data/model/pagination.py delete mode 100644 pinecone/core/openapi/db_data/model/protobuf_any.py delete mode 100644 pinecone/core/openapi/db_data/model/protobuf_null_value.py delete mode 100644 pinecone/core/openapi/db_data/model/query_request.py delete mode 100644 pinecone/core/openapi/db_data/model/query_response.py delete mode 100644 pinecone/core/openapi/db_data/model/query_vector.py delete mode 100644 pinecone/core/openapi/db_data/model/rpc_status.py delete mode 100644 pinecone/core/openapi/db_data/model/scored_vector.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_request.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_request_query.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_request_rerank.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_response.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_response_result.py delete mode 100644 pinecone/core/openapi/db_data/model/search_records_vector.py delete mode 100644 pinecone/core/openapi/db_data/model/search_usage.py delete mode 100644 pinecone/core/openapi/db_data/model/search_vector.py delete mode 100644 pinecone/core/openapi/db_data/model/single_query_results.py delete mode 100644 pinecone/core/openapi/db_data/model/sparse_values.py delete mode 100644 pinecone/core/openapi/db_data/model/start_import_request.py delete mode 100644 pinecone/core/openapi/db_data/model/start_import_response.py delete mode 100644 pinecone/core/openapi/db_data/model/update_request.py delete mode 100644 pinecone/core/openapi/db_data/model/upsert_record.py delete mode 100644 pinecone/core/openapi/db_data/model/upsert_request.py delete mode 100644 pinecone/core/openapi/db_data/model/upsert_response.py delete mode 100644 pinecone/core/openapi/db_data/model/usage.py delete mode 100644 pinecone/core/openapi/db_data/model/vector.py delete mode 100644 pinecone/core/openapi/db_data/model/vector_values.py delete mode 100644 pinecone/core/openapi/db_data/models/__init__.py delete mode 100644 pinecone/core/openapi/inference/__init__.py delete mode 100644 pinecone/core/openapi/inference/api/__init__.py delete mode 100644 pinecone/core/openapi/inference/api/inference_api.py delete mode 100644 pinecone/core/openapi/inference/apis/__init__.py delete mode 100644 pinecone/core/openapi/inference/model/__init__.py delete mode 100644 pinecone/core/openapi/inference/model/dense_embedding.py delete mode 100644 pinecone/core/openapi/inference/model/document.py delete mode 100644 pinecone/core/openapi/inference/model/embed_request.py delete mode 100644 pinecone/core/openapi/inference/model/embed_request_inputs.py delete mode 100644 pinecone/core/openapi/inference/model/embedding.py delete mode 100644 pinecone/core/openapi/inference/model/embeddings_list.py delete mode 100644 pinecone/core/openapi/inference/model/embeddings_list_usage.py delete mode 100644 pinecone/core/openapi/inference/model/error_response.py delete mode 100644 pinecone/core/openapi/inference/model/error_response_error.py delete mode 100644 pinecone/core/openapi/inference/model/ranked_document.py delete mode 100644 pinecone/core/openapi/inference/model/rerank_request.py delete mode 100644 pinecone/core/openapi/inference/model/rerank_result.py delete mode 100644 pinecone/core/openapi/inference/model/rerank_result_usage.py delete mode 100644 pinecone/core/openapi/inference/model/sparse_embedding.py delete mode 100644 pinecone/core/openapi/inference/model/vector_type.py delete mode 100644 pinecone/core/openapi/inference/models/__init__.py delete mode 100644 pinecone/data/__init__.py delete mode 100644 pinecone/data/dataclasses/__init__.py delete mode 100644 pinecone/data/dataclasses/fetch_response.py delete mode 100644 pinecone/data/dataclasses/search_query.py delete mode 100644 pinecone/data/dataclasses/search_query_vector.py delete mode 100644 pinecone/data/dataclasses/search_rerank.py delete mode 100644 pinecone/data/dataclasses/sparse_values.py delete mode 100644 pinecone/data/dataclasses/utils.py delete mode 100644 pinecone/data/dataclasses/vector.py delete mode 100644 pinecone/data/errors.py delete mode 100644 pinecone/data/features/__init__.py delete mode 100644 pinecone/data/features/bulk_import/__init__.py delete mode 100644 pinecone/data/features/bulk_import/bulk_import.py delete mode 100644 pinecone/data/features/bulk_import/bulk_import_asyncio.py delete mode 100644 pinecone/data/features/bulk_import/bulk_import_request_factory.py delete mode 100644 pinecone/data/features/inference/__init__.py delete mode 100644 pinecone/data/features/inference/inference.py delete mode 100644 pinecone/data/features/inference/inference_asyncio.py delete mode 100644 pinecone/data/features/inference/inference_request_builder.py delete mode 100644 pinecone/data/features/inference/models/__init__.py delete mode 100644 pinecone/data/features/inference/models/embedding_list.py delete mode 100644 pinecone/data/features/inference/models/rerank_result.py delete mode 100644 pinecone/data/features/inference/repl_overrides.py delete mode 100644 pinecone/data/import_error.py delete mode 100644 pinecone/data/index.py delete mode 100644 pinecone/data/index_asyncio.py delete mode 100644 pinecone/data/index_asyncio_interface.py delete mode 100644 pinecone/data/interfaces.py delete mode 100644 pinecone/data/query_results_aggregator.py delete mode 100644 pinecone/data/request_factory.py delete mode 100644 pinecone/data/sparse_values_factory.py delete mode 100644 pinecone/data/types/__init__.py delete mode 100644 pinecone/data/types/query_filter.py delete mode 100644 pinecone/data/types/search_query_typed_dict.py delete mode 100644 pinecone/data/types/search_query_vector_typed_dict.py delete mode 100644 pinecone/data/types/search_rerank_typed_dict.py delete mode 100644 pinecone/data/types/sparse_vector_typed_dict.py delete mode 100644 pinecone/data/types/vector_metadata_dict.py delete mode 100644 pinecone/data/types/vector_tuple.py delete mode 100644 pinecone/data/types/vector_typed_dict.py delete mode 100644 pinecone/data/vector_factory.py delete mode 100644 pinecone/deprecated_plugins.py delete mode 100644 pinecone/deprecation_warnings.py delete mode 100644 pinecone/enums/__init__.py delete mode 100644 pinecone/enums/clouds.py delete mode 100644 pinecone/enums/deletion_protection.py delete mode 100644 pinecone/enums/metric.py delete mode 100644 pinecone/enums/pod_index_environment.py delete mode 100644 pinecone/enums/pod_type.py delete mode 100644 pinecone/enums/vector_type.py delete mode 100644 pinecone/exceptions/__init__.py delete mode 100644 pinecone/exceptions/exceptions.py delete mode 100644 pinecone/grpc/__init__.py delete mode 100644 pinecone/grpc/base.py delete mode 100644 pinecone/grpc/channel_factory.py delete mode 100644 pinecone/grpc/config.py delete mode 100644 pinecone/grpc/future.py delete mode 100644 pinecone/grpc/grpc_runner.py delete mode 100644 pinecone/grpc/index_grpc.py delete mode 100644 pinecone/grpc/pinecone.py delete mode 100644 pinecone/grpc/retry.py delete mode 100644 pinecone/grpc/sparse_values_factory.py delete mode 100644 pinecone/grpc/utils.py delete mode 100644 pinecone/grpc/vector_factory_grpc.py delete mode 100644 pinecone/models/__init__.py delete mode 100644 pinecone/models/collection_description.py delete mode 100644 pinecone/models/collection_list.py delete mode 100644 pinecone/models/index_description.py delete mode 100644 pinecone/models/index_embed.py delete mode 100644 pinecone/models/index_list.py delete mode 100644 pinecone/models/index_model.py delete mode 100644 pinecone/models/list_response.py delete mode 100644 pinecone/models/pod_spec.py delete mode 100644 pinecone/models/serverless_spec.py delete mode 100644 pinecone/openapi_support/__init__.py delete mode 100644 pinecone/openapi_support/api_client.py delete mode 100644 pinecone/openapi_support/api_client_utils.py delete mode 100644 pinecone/openapi_support/api_version.py delete mode 100644 pinecone/openapi_support/asyncio_api_client.py delete mode 100644 pinecone/openapi_support/asyncio_endpoint.py delete mode 100644 pinecone/openapi_support/auth_util.py delete mode 100644 pinecone/openapi_support/cached_class_property.py delete mode 100644 pinecone/openapi_support/configuration.py delete mode 100644 pinecone/openapi_support/constants.py delete mode 100644 pinecone/openapi_support/deserializer.py delete mode 100644 pinecone/openapi_support/endpoint.py delete mode 100644 pinecone/openapi_support/endpoint_utils.py delete mode 100644 pinecone/openapi_support/exceptions.py delete mode 100644 pinecone/openapi_support/model_utils.py delete mode 100644 pinecone/openapi_support/rest_aiohttp.py delete mode 100644 pinecone/openapi_support/rest_urllib3.py delete mode 100644 pinecone/openapi_support/rest_utils.py delete mode 100644 pinecone/openapi_support/serializer.py delete mode 100644 pinecone/openapi_support/types.py delete mode 100644 pinecone/utils/__init__.py delete mode 100644 pinecone/utils/check_kwargs.py delete mode 100644 pinecone/utils/constants.py delete mode 100644 pinecone/utils/convert_enum_to_string.py delete mode 100644 pinecone/utils/convert_to_list.py delete mode 100644 pinecone/utils/deprecation_notice.py delete mode 100644 pinecone/utils/docslinks.py delete mode 100644 pinecone/utils/error_handling.py delete mode 100644 pinecone/utils/filter_dict.py delete mode 100644 pinecone/utils/fix_tuple_length.py delete mode 100644 pinecone/utils/normalize_host.py delete mode 100644 pinecone/utils/parse_args.py delete mode 100644 pinecone/utils/plugin_aware.py delete mode 100644 pinecone/utils/repr_overrides.py delete mode 100644 pinecone/utils/setup_openapi_client.py delete mode 100644 pinecone/utils/tqdm.py delete mode 100644 pinecone/utils/user_agent.py delete mode 100644 pinecone/utils/version.py diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 1a24c6154..414191733 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -11,19 +11,19 @@ jobs: linting: uses: './.github/workflows/lint.yaml' - unit-tests: - uses: './.github/workflows/testing-unit.yaml' - secrets: inherit + # unit-tests: + # uses: './.github/workflows/testing-unit.yaml' + # secrets: inherit - integration-tests: - uses: './.github/workflows/testing-integration.yaml' - secrets: inherit - needs: unit-tests + # integration-tests: + # uses: './.github/workflows/testing-integration.yaml' + # secrets: inherit + # needs: unit-tests - dependency-tests: - uses: './.github/workflows/testing-dependency.yaml' - secrets: inherit - needs: unit-tests + # dependency-tests: + # uses: './.github/workflows/testing-dependency.yaml' + # secrets: inherit + # needs: unit-tests package: name: Check packaging @@ -42,13 +42,13 @@ jobs: - name: Package run: poetry build - build-docs: - name: Build docs with pdoc - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Build docs with pdoc - uses: './.github/actions/build-docs' - with: - python-version: 3.11 + # build-docs: + # name: Build docs with pdoc + # runs-on: ubuntu-latest + # steps: + # - name: Checkout + # uses: actions/checkout@v4 + # - name: Build docs with pdoc + # uses: './.github/actions/build-docs' + # with: + # python-version: 3.11 diff --git a/.github/workflows/publish-to-pypi.yaml b/.github/workflows/publish-to-pypi.yaml index 655a848b0..3e5e80d86 100644 --- a/.github/workflows/publish-to-pypi.yaml +++ b/.github/workflows/publish-to-pypi.yaml @@ -65,7 +65,7 @@ jobs: - name: Verify unique release number run: | - TAG_NAME=${{ steps.bump.outputs.VERSION_TAG }} + TAG_NAME=pinecone-client-${{ steps.bump.outputs.VERSION_TAG }} if git rev-parse -q --verify "refs/tags/$TAG_NAME" >/dev/null; then echo "Tag $TAG_NAME already exists." exit 1 diff --git a/README.md b/README.md index d45824b9c..61ac0454b 100644 --- a/README.md +++ b/README.md @@ -1,210 +1,6 @@ -# Pinecone Python SDK -![License](https://img.shields.io/github/license/pinecone-io/pinecone-python-client?color=orange) [![CI](https://github.com/pinecone-io/pinecone-python-client/actions/workflows/pr.yaml/badge.svg)](https://github.com/pinecone-io/pinecone-python-client/actions/workflows/pr.yaml) +# Pinecone Python Client (DEPRECATED) -The official Pinecone Python SDK. +The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please update your projects to consume future updates using the `pinecone` package name. -For more information, see the docs at https://docs.pinecone.io - - -## Documentation - -- [**Reference Documentation**](https://sdk.pinecone.io/python/index.html) - -### Upgrading the SDK - -For notes on changes between major versions, see [Upgrading](./docs/upgrading.md) - -## Prerequisites - -- The Pinecone Python SDK is compatible with Python 3.9 and greater. It has been tested with CPython versions from 3.9 to 3.13. -- Before you can use the Pinecone SDK, you must sign up for an account and find your API key in the Pinecone console dashboard at [https://app.pinecone.io](https://app.pinecone.io). - -## Installation - -The Pinecone Python SDK is distributed on PyPI using the package name `pinecone`. By default the `pinecone` has a minimal set of dependencies, but you can install some extras to unlock additional functionality. - -Available extras: - -- `pinecone[asyncio]` will add a dependency on `aiohttp` and enable usage of `PineconeAsyncio`, the asyncio-enabled version of the client for use with highly asynchronous modern web frameworks such as FastAPI. -- `pinecone[grpc]` will add dependencies on `grpcio` and related libraries needed to make pinecone data calls such as `upsert` and `query` over [GRPC](https://grpc.io/) for a modest performance improvement. See the guide on [tuning performance](https://docs.pinecone.io/docs/performance-tuning). - -#### Installing with pip - -```shell -# Install the latest version -pip3 install pinecone - -# Install the latest version, with optional dependencies -pip3 install "pinecone[asyncio,grpc]" -``` - -#### Installing with uv - -[uv](https://docs.astral.sh/uv/) is a modern package manager that runs 10-100x faster than pip and supports most pip syntax. - -```shell -# Install the latest version -uv install pinecone - -# Install the latest version, optional dependencies -uv install "pinecone[asyncio,grpc]" -``` - -#### Installing with [poetry](https://python-poetry.org/) - -```shell -# Install the latest version -poetry add pinecone - -# Install the latest version, with optional dependencies -poetry add pinecone --extras asyncio --extras grpc -``` - -# Quickstart - -## Bringing your own vectors to Pinecone - -```python -from pinecone import ( - Pinecone, - ServerlessSpec, - CloudProvider, - AwsRegion, - VectorType -) - -# 1. Instantiate the Pinecone client -pc = Pinecone(api_key='YOUR_API_KEY') - -# 2. Create an index -index_config = pc.create_index( - name="index-name", - dimension=1536, - spec=ServerlessSpec( - cloud=CloudProvider.AWS, - region=AwsRegion.US_EAST_1 - ), - vector_type=VectorType.DENSE -) - -# 3. Instantiate an Index client -idx = pc.Index(host=index_config.host) - -# 4. Upsert embeddings -idx.upsert( - vectors=[ - ("id1", [0.1, 0.2, 0.3, 0.4, ...], {"metadata_key": "value1"}), - ("id2", [0.2, 0.3, 0.4, 0.5, ...], {"metadata_key": "value2"}), - ], - namespace="example-namespace" -) - -# 5. Query your index using an embedding -query_embedding = [...] # list should have length == index dimension -idx.query( - vector=query_embedding, - top_k=10, - include_metadata=True, - filter={"metadata_key": { "$eq": "value1" }} -) -``` - -## Bring your own data using Pinecone integrated inference - -```python -from pinecone import ( - Pinecone, - CloudProvider, - AwsRegion, - EmbedModel, -) - -# 1. Instantiate the Pinecone client -pc = Pinecone(api_key="<>") - -# 2. Create an index configured for use with a particular model -index_config = pc.create_index_for_model( - name="my-model-index", - cloud=CloudProvider.AWS, - region=AwsRegion.US_EAST_1, - embed=IndexEmbed( - model=EmbedModel.Multilingual_E5_Large, - field_map={"text": "my_text_field"} - ) -) - -# 3. Instantiate an Index client -idx = pc.Index(host=index_config.host) - -# 4. Upsert records -idx.upsert_records( - namespace="my-namespace", - records=[ - { - "_id": "test1", - "my_text_field": "Apple is a popular fruit known for its sweetness and crisp texture.", - }, - { - "_id": "test2", - "my_text_field": "The tech company Apple is known for its innovative products like the iPhone.", - }, - { - "_id": "test3", - "my_text_field": "Many people enjoy eating apples as a healthy snack.", - }, - { - "_id": "test4", - "my_text_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - }, - { - "_id": "test5", - "my_text_field": "An apple a day keeps the doctor away, as the saying goes.", - }, - { - "_id": "test6", - "my_text_field": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.", - }, - ], -) - -# 5. Search for similar records -from pinecone import SearchQuery, SearchRerank, RerankModel - -response = index.search_records( - namespace="my-namespace", - query=SearchQuery( - inputs={ - "text": "Apple corporation", - }, - top_k=3 - ), - rerank=SearchRerank( - model=RerankModel.Bge_Reranker_V2_M3, - rank_fields=["my_text_field"], - top_n=3, - ), -) -``` - -## More information on usage - -Detailed information on specific ways of using the SDK are covered in these other pages. - -- Store and query your vectors - - [Serverless Indexes](./docs/db_control/serverless-indexes.md) - - [Pod Indexes](./docs/db_control/pod-indexes.md) - - [Working with vectors](./docs/db_data/index-usage-byov.md) - -- [Inference API](./docs/inference-api.md) -- [FAQ](./docs/faq.md) - - -# Issues & Bugs - -If you notice bugs or have feedback, please [file an issue](https://github.com/pinecone-io/pinecone-python-client/issues). - -You can also get help in the [Pinecone Community Forum](https://community.pinecone.io/). - -# Contributing - -If you'd like to make a contribution, or get setup locally to develop the Pinecone Python SDK, please see our [contributing guide](https://github.com/pinecone-io/pinecone-python-client/blob/main/CONTRIBUTING.md) +- [`pinecone`](https://pypi.org/project/pinecone/) on PyPI +- [Source on Github](https://github.com/pinecone-io/pinecone-python-client) diff --git a/codegen/apis b/codegen/apis index eb79d8ea0..29ca869fc 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit eb79d8ea0c146aebe36c3769e19cbe9618db2d54 +Subproject commit 29ca869fc2a1f2a0f7d0ae9a61085059febfae66 diff --git a/pinecone/__init__.py b/pinecone/__init__.py index d1f2b132a..dcc73b8f7 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -2,22 +2,6 @@ .. include:: ../README.md """ -from .deprecated_plugins import check_for_deprecated_plugins -from .deprecation_warnings import * -from .config import * -from .exceptions import * -from .control import * -from .data import * -from .models import * -from .enums import * - -from .utils import __version__ - -import logging - -# Raise an exception if the user is attempting to use the SDK with -# deprecated plugins installed in their project. -check_for_deprecated_plugins() - -# Silence annoying log messages from the plugin interface -logging.getLogger("pinecone_plugin_interface").setLevel(logging.CRITICAL) +raise Exception( + "The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please update your projects to use the `pinecone` package name. See the README at https://github.com/pinecone-io/pinecone-python-client for more information." +) diff --git a/pinecone/config/__init__.py b/pinecone/config/__init__.py deleted file mode 100644 index 7abb7278e..000000000 --- a/pinecone/config/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -import logging -import os - -from .config import ConfigBuilder, Config -from .pinecone_config import PineconeConfig - -if os.getenv("PINECONE_DEBUG") is not None: - logging.getLogger("pinecone").setLevel(level=logging.DEBUG) diff --git a/pinecone/config/config.py b/pinecone/config/config.py deleted file mode 100644 index 01a703e0b..000000000 --- a/pinecone/config/config.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import NamedTuple, Optional, Dict -import os - -from pinecone.exceptions.exceptions import PineconeConfigurationError -from pinecone.config.openapi import OpenApiConfigFactory -from pinecone.openapi_support.configuration import Configuration as OpenApiConfiguration - - -# Duplicated this util to help resolve circular imports -def normalize_host(host: Optional[str]) -> str: - if host is None: - return "" - if host.startswith("https://"): - return host - if host.startswith("http://"): - return host - return "https://" + host - - -class Config(NamedTuple): - api_key: str = "" - host: str = "" - proxy_url: Optional[str] = None - proxy_headers: Optional[Dict[str, str]] = None - ssl_ca_certs: Optional[str] = None - ssl_verify: Optional[bool] = None - additional_headers: Optional[Dict[str, str]] = {} - source_tag: Optional[str] = None - - -class ConfigBuilder: - """ - - 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. - """ - - @staticmethod - def build( - api_key: Optional[str] = None, - host: Optional[str] = None, - proxy_url: Optional[str] = None, - proxy_headers: Optional[Dict[str, str]] = None, - ssl_ca_certs: Optional[str] = None, - ssl_verify: Optional[bool] = None, - additional_headers: Optional[Dict[str, str]] = {}, - **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) - host = normalize_host(host) - source_tag = kwargs.pop("source_tag", None) - - if not api_key: - raise PineconeConfigurationError( - "You haven't specified an API key. Please either set the PINECONE_API_KEY environment variable or pass the 'api_key' keyword argument to the Pinecone client constructor." - ) - if not host: - raise PineconeConfigurationError("You haven't specified a host.") - - return Config( - api_key, - host, - proxy_url, - proxy_headers, - ssl_ca_certs, - ssl_verify, - additional_headers, - source_tag, - ) - - @staticmethod - def build_openapi_config( - config: Config, openapi_config: Optional[OpenApiConfiguration] = None, **kwargs - ) -> OpenApiConfiguration: - if openapi_config: - openapi_config = OpenApiConfigFactory.copy( - openapi_config=openapi_config, api_key=config.api_key, host=config.host - ) - elif openapi_config is None: - openapi_config = OpenApiConfigFactory.build(api_key=config.api_key, host=config.host) - - # Check if value passed before overriding any values present - # in the openapi_config. This means if the user has passed - # an openapi_config object and a kwarg for the same setting, - # the kwarg will take precedence. - if config.proxy_url: - openapi_config.proxy = config.proxy_url - if config.proxy_headers: - openapi_config.proxy_headers = config.proxy_headers - if config.ssl_ca_certs: - openapi_config.ssl_ca_cert = config.ssl_ca_certs - if config.ssl_verify is not None: - openapi_config.verify_ssl = config.ssl_verify - - return openapi_config diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py deleted file mode 100644 index d6bdf7028..000000000 --- a/pinecone/config/openapi.py +++ /dev/null @@ -1,106 +0,0 @@ -import sys -from typing import List, Optional - -import certifi -import socket -import copy - -from urllib3.connection import HTTPConnection - -from pinecone.openapi_support.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: Optional[str] = None, **kwargs): - openapi_config = OpenApiConfiguration() - openapi_config.api_key = {"ApiKeyAuth": api_key} - openapi_config.host = host - openapi_config.ssl_ca_cert = certifi.where() - openapi_config.socket_options = cls._get_socket_options() - openapi_config.discard_unknown_keys = True - - return openapi_config - - @classmethod - def copy( - cls, openapi_config: OpenApiConfiguration, api_key: str, host: str - ) -> OpenApiConfiguration: - """ - Copy a user-supplied openapi configuration and update it with the user's api key and host. - If they have not specified other socket configuration, we will use the default values. - We expect these objects are being passed mainly a vehicle for proxy configuration, so - we don't modify those settings. - """ - copied = copy.deepcopy(openapi_config) - - copied.api_key = {"ApiKeyAuth": api_key} - copied.host = host - - # Set sensible defaults if the user hasn't set them - if not copied.socket_options: - copied.socket_options = cls._get_socket_options() - - # We specifically do not modify the user's ssl_ca_cert or proxy settings, as - # they may have set them intentionally. This is the main reason somebody would - # pass an openapi_config in the first place. - - return copied - - @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, - 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 deleted file mode 100644 index ad8125fc0..000000000 --- a/pinecone/config/pinecone_config.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Optional, Dict -import logging -import json -import os -from .config import ConfigBuilder, Config - -logger = logging.getLogger(__name__) -""" @private """ - -DEFAULT_CONTROLLER_HOST = "https://api.pinecone.io" - - -class PineconeConfig: - @staticmethod - 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 - ) - headers_json = os.getenv("PINECONE_ADDITIONAL_HEADERS") - if headers_json: - try: - headers = json.loads(headers_json) - additional_headers = additional_headers or headers - except Exception as e: - logger.warn(f"Ignoring PINECONE_ADDITIONAL_HEADERS: {e}") - - return ConfigBuilder.build( - api_key=api_key, host=host, additional_headers=additional_headers, **kwargs - ) diff --git a/pinecone/control/__init__.py b/pinecone/control/__init__.py deleted file mode 100644 index a26e352ae..000000000 --- a/pinecone/control/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .pinecone import Pinecone -from .pinecone_asyncio import PineconeAsyncio - -from .repr_overrides import install_repr_overrides - -install_repr_overrides() diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py deleted file mode 100644 index eec2e7efe..000000000 --- a/pinecone/control/index_host_store.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Dict -from pinecone.config import Config -from pinecone.core.openapi.db_control.api.manage_indexes_api import ( - ManageIndexesApi as IndexOperationsApi, -) -from pinecone.openapi_support.exceptions import PineconeException -from pinecone.utils import normalize_host - - -class SingletonMeta(type): - _instances: Dict[str, str] = {} - - 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): - _indexHosts: Dict[str, str] - - def __init__(self) -> None: - 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 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) - self._indexHosts[key] = normalize_host(host) - - def get_host(self, api: IndexOperationsApi, config: Config, index_name: str) -> str: - key = self._key(config, index_name) - if self.key_exists(key): - return self._indexHosts[key] - else: - description = api.describe_index(index_name) - self.set_host(config, index_name, description.host) - if not self.key_exists(key): - 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/control/langchain_import_warnings.py b/pinecone/control/langchain_import_warnings.py deleted file mode 100644 index ac55ef572..000000000 --- a/pinecone/control/langchain_import_warnings.py +++ /dev/null @@ -1,9 +0,0 @@ -from pinecone.utils import docslinks - -KB_ARTICLE = docslinks["LANGCHAIN_IMPORT_KB_ARTICLE"] -GITHUB_REPO = docslinks["GITHUB_REPO"] - - -def _build_langchain_attribute_error_message(method_name: str): - return f"""{method_name} is not a top-level attribute of the Pinecone class provided by pinecone's official python package developed at {GITHUB_REPO}. You may have a name collision with an export from another dependency in your project that wraps Pinecone functionality and exports a similarly named class. Please refer to the following knowledge base article for more information: {KB_ARTICLE} -""" diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py deleted file mode 100644 index f3c8f4042..000000000 --- a/pinecone/control/pinecone.py +++ /dev/null @@ -1,354 +0,0 @@ -import time -import logging -from typing import Optional, Dict, Union -from multiprocessing import cpu_count - -from .index_host_store import IndexHostStore -from .pinecone_interface import PineconeDBControlInterface - -from pinecone.config import PineconeConfig, ConfigBuilder - -from pinecone.core.openapi.db_control.api.manage_indexes_api import ManageIndexesApi -from pinecone.openapi_support.api_client import ApiClient - - -from pinecone.utils import normalize_host, setup_openapi_client, PluginAware -from pinecone.core.openapi.db_control import API_VERSION -from pinecone.models import ( - ServerlessSpec, - PodSpec, - IndexModel, - IndexList, - CollectionList, - IndexEmbed, -) -from .langchain_import_warnings import _build_langchain_attribute_error_message -from pinecone.utils import docslinks -from pinecone.data import _Index, _Inference, _IndexAsyncio - -from pinecone.enums import ( - Metric, - VectorType, - DeletionProtection, - PodType, - CloudProvider, - AwsRegion, - GcpRegion, - AzureRegion, -) -from .types import CreateIndexForModelEmbedTypedDict -from .request_factory import PineconeDBControlRequestFactory - -logger = logging.getLogger(__name__) -""" @private """ - - -class Pinecone(PineconeDBControlInterface, PluginAware): - """ - A client for interacting with Pinecone's vector database. - - This class implements methods for managing and interacting with Pinecone resources - such as collections and indexes. - """ - - def __init__( - self, - api_key: Optional[str] = None, - host: Optional[str] = None, - proxy_url: Optional[str] = None, - proxy_headers: Optional[Dict[str, str]] = None, - ssl_ca_certs: Optional[str] = None, - ssl_verify: Optional[bool] = None, - additional_headers: Optional[Dict[str, str]] = {}, - pool_threads: Optional[int] = None, - **kwargs, - ): - for deprecated_kwarg in {"config", "openapi_config", "index_api"}: - if deprecated_kwarg in kwargs: - raise NotImplementedError( - f"Passing {deprecated_kwarg} is no longer supported. Please pass individual settings such as proxy_url, proxy_headers, ssl_ca_certs, and ssl_verify directly to the Pinecone constructor as keyword arguments. See the README at {docslinks['README']} for examples." - ) - - self.config = PineconeConfig.build( - api_key=api_key, - host=host, - additional_headers=additional_headers, - proxy_url=proxy_url, - proxy_headers=proxy_headers, - ssl_ca_certs=ssl_ca_certs, - ssl_verify=ssl_verify, - **kwargs, - ) - """ @private """ - - self.openapi_config = ConfigBuilder.build_openapi_config(self.config, **kwargs) - """ @private """ - - if pool_threads is None: - self.pool_threads = 5 * cpu_count() - """ @private """ - else: - self.pool_threads = pool_threads - """ @private """ - - self._inference = None # Lazy initialization - """ @private """ - - self.index_api = setup_openapi_client( - api_client_klass=ApiClient, - api_klass=ManageIndexesApi, - config=self.config, - openapi_config=self.openapi_config, - pool_threads=pool_threads, - api_version=API_VERSION, - ) - """ @private """ - - self.index_host_store = IndexHostStore() - """ @private """ - - self.load_plugins( - config=self.config, openapi_config=self.openapi_config, pool_threads=self.pool_threads - ) - - @property - def inference(self): - """ - Inference is a namespace where an instance of the `pinecone.data.features.inference.inference.Inference` class is lazily created and cached. - """ - if self._inference is None: - self._inference = _Inference(config=self.config, openapi_config=self.openapi_config) - return self._inference - - def create_index( - self, - name: str, - spec: Union[Dict, ServerlessSpec, PodSpec], - dimension: Optional[int] = None, - metric: Optional[Union[Metric, str]] = Metric.COSINE, - timeout: Optional[int] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - vector_type: Optional[Union[VectorType, str]] = VectorType.DENSE, - tags: Optional[Dict[str, str]] = None, - ) -> IndexModel: - req = PineconeDBControlRequestFactory.create_index_request( - name=name, - spec=spec, - dimension=dimension, - metric=metric, - deletion_protection=deletion_protection, - vector_type=vector_type, - tags=tags, - ) - resp = self.index_api.create_index(create_index_request=req) - - if timeout == -1: - return IndexModel(resp) - return self.__poll_describe_index_until_ready(name, timeout) - - def create_index_for_model( - self, - name: str, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - embed: Union[IndexEmbed, CreateIndexForModelEmbedTypedDict], - tags: Optional[Dict[str, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - timeout: Optional[int] = None, - ) -> IndexModel: - req = PineconeDBControlRequestFactory.create_index_for_model_request( - name=name, - cloud=cloud, - region=region, - embed=embed, - tags=tags, - deletion_protection=deletion_protection, - ) - resp = self.index_api.create_index_for_model(req) - - if timeout == -1: - return IndexModel(resp) - return self.__poll_describe_index_until_ready(name, timeout) - - def __poll_describe_index_until_ready(self, name: str, timeout: Optional[int] = None): - description = None - - def is_ready() -> bool: - nonlocal description - description = self.describe_index(name=name) - return description.status.ready - - total_wait_time = 0 - if timeout is None: - # Wait indefinitely - while not is_ready(): - logger.debug( - f"Waiting for index {name} to be ready. Total wait time {total_wait_time} seconds." - ) - total_wait_time += 5 - time.sleep(5) - - else: - # Wait for a maximum of timeout seconds - while not is_ready(): - if timeout < 0: - logger.error(f"Index {name} is not ready. Timeout reached.") - link = docslinks["API_DESCRIBE_INDEX"] - timeout_msg = ( - f"Please call describe_index() to confirm index status. See docs at {link}" - ) - raise TimeoutError(timeout_msg) - - logger.debug( - f"Waiting for index {name} to be ready. Total wait time: {total_wait_time}" - ) - total_wait_time += 5 - time.sleep(5) - timeout -= 5 - - return description - - def delete_index(self, name: str, timeout: Optional[int] = None): - self.index_api.delete_index(name) - self.index_host_store.delete_host(self.config, name) - - if timeout == -1: - return - - if timeout is None: - while self.has_index(name): - time.sleep(5) - else: - while self.has_index(name) 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) -> IndexList: - response = self.index_api.list_indexes() - return IndexList(response) - - def describe_index(self, name: str) -> IndexModel: - api_instance = self.index_api - description = api_instance.describe_index(name) - host = description.host - self.index_host_store.set_host(self.config, name, host) - - return IndexModel(description) - - def has_index(self, name: str) -> bool: - if name in self.list_indexes().names(): - return True - else: - return False - - def configure_index( - self, - name: str, - replicas: Optional[int] = None, - pod_type: Optional[Union[PodType, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = None, - tags: Optional[Dict[str, str]] = None, - ): - api_instance = self.index_api - description = self.describe_index(name=name) - - req = PineconeDBControlRequestFactory.configure_index_request( - description=description, - replicas=replicas, - pod_type=pod_type, - deletion_protection=deletion_protection, - tags=tags, - ) - api_instance.configure_index(name, configure_index_request=req) - - def create_collection(self, name: str, source: str) -> None: - req = PineconeDBControlRequestFactory.create_collection_request(name=name, source=source) - self.index_api.create_collection(create_collection_request=req) - - def list_collections(self) -> CollectionList: - response = self.index_api.list_collections() - return CollectionList(response) - - def delete_collection(self, name: str) -> None: - self.index_api.delete_collection(name) - - def describe_collection(self, name: str): - return self.index_api.describe_collection(name).to_dict() - - @staticmethod - def from_texts(*args, **kwargs): - """@private""" - raise AttributeError(_build_langchain_attribute_error_message("from_texts")) - - @staticmethod - def from_documents(*args, **kwargs): - """@private""" - raise AttributeError(_build_langchain_attribute_error_message("from_documents")) - - def Index(self, name: str = "", host: str = "", **kwargs): - if name == "" and host == "": - raise ValueError("Either name or host must be specified") - - pt = kwargs.pop("pool_threads", None) or self.pool_threads - api_key = self.config.api_key - openapi_config = self.openapi_config - - if host != "": - check_realistic_host(host) - - # Use host url if it is provided - index_host = normalize_host(host) - else: - # Otherwise, get host url from describe_index using the index name - index_host = self.index_host_store.get_host(self.index_api, self.config, name) - - return _Index( - host=index_host, - api_key=api_key, - pool_threads=pt, - openapi_config=openapi_config, - source_tag=self.config.source_tag, - **kwargs, - ) - - def IndexAsyncio(self, host: str, **kwargs): - api_key = self.config.api_key - openapi_config = self.openapi_config - - if host is None or host == "": - raise ValueError("A host must be specified") - - check_realistic_host(host) - index_host = normalize_host(host) - - return _IndexAsyncio( - host=index_host, - api_key=api_key, - openapi_config=openapi_config, - source_tag=self.config.source_tag, - **kwargs, - ) - - -def check_realistic_host(host: str) -> None: - """@private - - Checks whether a user-provided host string seems plausible. - Someone could erroneously pass an index name as the host by - mistake, and if they have done that we'd like to give them a - simple error message as feedback rather than attempting to - call the url and getting a more cryptic DNS resolution error. - """ - - if "." not in host and "localhost" not in host: - raise ValueError( - f"You passed '{host}' as the host but this does not appear to be valid. Call describe_index() to confirm the host of the index." - ) diff --git a/pinecone/control/pinecone_asyncio.py b/pinecone/control/pinecone_asyncio.py deleted file mode 100644 index 1373c8e41..000000000 --- a/pinecone/control/pinecone_asyncio.py +++ /dev/null @@ -1,340 +0,0 @@ -import logging -import asyncio -from typing import Optional, Dict, Union - -from pinecone.config import PineconeConfig, ConfigBuilder - -from pinecone.core.openapi.db_control.api.manage_indexes_api import AsyncioManageIndexesApi -from pinecone.openapi_support import AsyncioApiClient - -from pinecone.utils import normalize_host, setup_async_openapi_client -from pinecone.core.openapi.db_control import API_VERSION -from pinecone.models import ( - ServerlessSpec, - PodSpec, - IndexModel, - IndexList, - CollectionList, - IndexEmbed, -) -from pinecone.utils import docslinks - -from pinecone.data import _IndexAsyncio, _AsyncioInference -from pinecone.enums import ( - Metric, - VectorType, - DeletionProtection, - PodType, - CloudProvider, - AwsRegion, - GcpRegion, - AzureRegion, -) -from .types import CreateIndexForModelEmbedTypedDict -from .request_factory import PineconeDBControlRequestFactory -from .pinecone_interface_asyncio import PineconeAsyncioDBControlInterface -from .pinecone import check_realistic_host - -logger = logging.getLogger(__name__) -""" @private """ - - -class PineconeAsyncio(PineconeAsyncioDBControlInterface): - """ - `PineconeAsyncio` is an asyncio client for interacting with Pinecone's control plane API. - - This class implements methods for managing and interacting with Pinecone resources - such as collections and indexes. - - To perform data operations such as inserting and querying vectors, use the `IndexAsyncio` class. - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="my-index.pinecone.io") as idx: - await idx.upsert(vectors=[(1, [1, 2, 3]), (2, [4, 5, 6])]) - - asyncio.run(main()) - ``` - """ - - def __init__( - self, - api_key: Optional[str] = None, - host: Optional[str] = None, - proxy_url: Optional[str] = None, - # proxy_headers: Optional[Dict[str, str]] = None, - ssl_ca_certs: Optional[str] = None, - ssl_verify: Optional[bool] = None, - additional_headers: Optional[Dict[str, str]] = {}, - **kwargs, - ): - for deprecated_kwarg in {"config", "openapi_config"}: - if deprecated_kwarg in kwargs: - raise NotImplementedError( - f"Passing {deprecated_kwarg} is no longer supported. Please pass individual settings such as proxy_url, ssl_ca_certs, and ssl_verify directly to the Pinecone constructor as keyword arguments. See the README at {docslinks['README']} for examples." - ) - - for unimplemented_kwarg in {"proxy_headers"}: - if unimplemented_kwarg in kwargs: - raise NotImplementedError( - f"You have passed {unimplemented_kwarg} but this configuration has not been implemented for PineconeAsyncio." - ) - - self.config = PineconeConfig.build( - api_key=api_key, - host=host, - additional_headers=additional_headers, - proxy_url=proxy_url, - proxy_headers=None, - ssl_ca_certs=ssl_ca_certs, - ssl_verify=ssl_verify, - **kwargs, - ) - """ @private """ - - self.openapi_config = ConfigBuilder.build_openapi_config(self.config, **kwargs) - """ @private """ - - self._inference = None # Lazy initialization - """ @private """ - - self.index_api = setup_async_openapi_client( - api_client_klass=AsyncioApiClient, - api_klass=AsyncioManageIndexesApi, - config=self.config, - openapi_config=self.openapi_config, - api_version=API_VERSION, - ) - """ @private """ - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_value, traceback): - await self.close() - - async def close(self): - """Cleanup resources used by the Pinecone client. - - This method should be called when the client is no longer needed so that - it can cleanup the aioahttp session and other resources. - - After close has been called, the client instance should not be used. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - pc = PineconeAsyncio() - desc = await pc.describe_index(name="my-index") - await pc.close() - - asyncio.run(main()) - ``` - - If you are using the client as a context manager, the close method is called automatically - when exiting. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - desc = await pc.describe_index(name="my-index") - - # No need to call close in this case because the "async with" syntax - # automatically calls close when exiting the block. - asyncio.run(main()) - ``` - - """ - await self.index_api.api_client.close() - - @property - def inference(self): - """Dynamically create and cache the Inference instance.""" - if self._inference is None: - self._inference = _AsyncioInference(api_client=self.index_api.api_client) - return self._inference - - async def create_index( - self, - name: str, - spec: Union[Dict, ServerlessSpec, PodSpec], - dimension: Optional[int] = None, - metric: Optional[Union[Metric, str]] = Metric.COSINE, - timeout: Optional[int] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - vector_type: Optional[Union[VectorType, str]] = VectorType.DENSE, - tags: Optional[Dict[str, str]] = None, - ) -> IndexModel: - req = PineconeDBControlRequestFactory.create_index_request( - name=name, - spec=spec, - dimension=dimension, - metric=metric, - deletion_protection=deletion_protection, - vector_type=vector_type, - tags=tags, - ) - resp = await self.index_api.create_index(create_index_request=req) - - if timeout == -1: - return IndexModel(resp) - return await self.__poll_describe_index_until_ready(name, timeout) - - async def create_index_for_model( - self, - name: str, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - embed: Union[IndexEmbed, CreateIndexForModelEmbedTypedDict], - tags: Optional[Dict[str, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - timeout: Optional[int] = None, - ) -> IndexModel: - req = PineconeDBControlRequestFactory.create_index_for_model_request( - name=name, - cloud=cloud, - region=region, - embed=embed, - tags=tags, - deletion_protection=deletion_protection, - ) - resp = await self.index_api.create_index_for_model(req) - - if timeout == -1: - return IndexModel(resp) - return await self.__poll_describe_index_until_ready(name, timeout) - - async def __poll_describe_index_until_ready(self, name: str, timeout: Optional[int] = None): - description = None - - async def is_ready() -> bool: - nonlocal description - description = await self.describe_index(name=name) - return description.status.ready - - total_wait_time = 0 - if timeout is None: - # Wait indefinitely - while not await is_ready(): - logger.debug( - f"Waiting for index {name} to be ready. Total wait time {total_wait_time} seconds." - ) - total_wait_time += 5 - await asyncio.sleep(5) - - else: - # Wait for a maximum of timeout seconds - while not await is_ready(): - if timeout < 0: - logger.error(f"Index {name} is not ready. Timeout reached.") - link = docslinks["API_DESCRIBE_INDEX"] - timeout_msg = ( - f"Please call describe_index() to confirm index status. See docs at {link}" - ) - raise TimeoutError(timeout_msg) - - logger.debug( - f"Waiting for index {name} to be ready. Total wait time: {total_wait_time}" - ) - total_wait_time += 5 - await asyncio.sleep(5) - timeout -= 5 - - return description - - async def delete_index(self, name: str, timeout: Optional[int] = None): - await self.index_api.delete_index(name) - - if timeout == -1: - return - - if timeout is None: - while await self.has_index(name): - await asyncio.sleep(5) - else: - while await self.has_index(name) and timeout >= 0: - await asyncio.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/" - ) - ) - ) - - async def list_indexes(self) -> IndexList: - response = await self.index_api.list_indexes() - return IndexList(response) - - async def describe_index(self, name: str) -> IndexModel: - description = await self.index_api.describe_index(name) - return IndexModel(description) - - async def has_index(self, name: str) -> bool: - available_indexes = await self.list_indexes() - if name in available_indexes.names(): - return True - else: - return False - - async def configure_index( - self, - name: str, - replicas: Optional[int] = None, - pod_type: Optional[Union[PodType, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = None, - tags: Optional[Dict[str, str]] = None, - ): - description = await self.describe_index(name=name) - - req = PineconeDBControlRequestFactory.configure_index_request( - description=description, - replicas=replicas, - pod_type=pod_type, - deletion_protection=deletion_protection, - tags=tags, - ) - await self.index_api.configure_index(name, configure_index_request=req) - - async def create_collection(self, name: str, source: str): - req = PineconeDBControlRequestFactory.create_collection_request(name=name, source=source) - await self.index_api.create_collection(create_collection_request=req) - - async def list_collections(self) -> CollectionList: - response = await self.index_api.list_collections() - return CollectionList(response) - - async def delete_collection(self, name: str): - await self.index_api.delete_collection(name) - - async def describe_collection(self, name: str): - return await self.index_api.describe_collection(name).to_dict() - - def IndexAsyncio(self, host: str, **kwargs) -> _IndexAsyncio: - api_key = self.config.api_key - openapi_config = self.openapi_config - - if host is None or host == "": - raise ValueError("A host must be specified") - - check_realistic_host(host) - index_host = normalize_host(host) - - return _IndexAsyncio( - host=index_host, - api_key=api_key, - openapi_config=openapi_config, - source_tag=self.config.source_tag, - **kwargs, - ) diff --git a/pinecone/control/pinecone_interface.py b/pinecone/control/pinecone_interface.py deleted file mode 100644 index c183e6119..000000000 --- a/pinecone/control/pinecone_interface.py +++ /dev/null @@ -1,792 +0,0 @@ -from abc import ABC, abstractmethod - -from typing import Optional, Dict, Union - - -from pinecone.models import ( - ServerlessSpec, - PodSpec, - IndexList, - CollectionList, - IndexModel, - IndexEmbed, -) -from pinecone.enums import ( - Metric, - VectorType, - DeletionProtection, - PodType, - CloudProvider, - AwsRegion, - GcpRegion, - AzureRegion, -) -from .types import CreateIndexForModelEmbedTypedDict - - -class PineconeDBControlInterface(ABC): - @abstractmethod - def __init__( - self, - api_key: Optional[str] = None, - host: Optional[str] = None, - proxy_url: Optional[str] = None, - proxy_headers: Optional[Dict[str, str]] = None, - ssl_ca_certs: Optional[str] = None, - ssl_verify: Optional[bool] = None, - additional_headers: Optional[Dict[str, str]] = {}, - pool_threads: Optional[int] = 1, - **kwargs, - ): - """ - The `Pinecone` class is the main entry point for interacting with Pinecone via this Python SDK. - Instances of the `Pinecone` class are used to create, delete, and manage your indexes and collections. The class also holds inference functionality (embed, rerank) under the `inference` namespace. - Methods which create or modify index and collection resources result in network calls to https://api.pinecone.io. - - When you are ready to perform data operations on an index, you will need to instantiate an index client. Though the functionality of the index client is defined in a different - class, it is instantiated through the `Index()` method in order for configurations to be shared between the two objects. - - :param api_key: The API key to use for authentication. If not passed via kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - :type api_key: str, optional - :param host: The control plane host. If unspecified, the host `api.pinecone.io` will be used. - :type host: str, optional - :param proxy_url: The URL of the proxy to use for the connection. - :type proxy_url: str, optional - :param proxy_headers: Additional headers to pass to the proxy. Use this if your proxy setup requires authentication. - :type proxy_headers: Dict[str, str], optional - :param ssl_ca_certs: The path to the SSL CA certificate bundle to use for the connection. This path should point to a file in PEM format. When not passed, the SDK will use the certificate bundle returned from `certifi.where()`. - :type ssl_ca_certs: str, optional - :param ssl_verify: SSL verification is performed by default, but can be disabled using the boolean flag when testing with Pinecone Local or troubleshooting a proxy setup. You should never run with SSL verification disabled in production. - :type ssl_verify: bool, optional - :param additional_headers: Additional headers to pass to the API. This is mainly to support internal testing at Pinecone. End users should not need to use this unless following specific instructions to do so. - :type additional_headers: Dict[str, str], optional - :param pool_threads: The number of threads to use for the ThreadPool when using methods that support the `async_req` keyword argument. The default number of threads is 5 * the number of CPUs in your execution environment. - :type pool_threads: int, optional - - ### Configuration with environment variables - - If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - ``` - - ### Configuration with keyword arguments - - If you prefer being more explicit in your code, you can also pass the API key as a keyword argument. This is also where you will pass additional configuration options such as proxy settings if you wish to use those. - - ```python - import os - from pinecone import Pinecone - - pc = Pinecone( - api_key=os.environ.get("PINECONE_API_KEY"), - host="https://api-staging.pinecone.io" - ) - ``` - - ### Environment variables - - The Pinecone client supports the following environment variables: - - - `PINECONE_API_KEY`: The API key to use for authentication. If not passed via - kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - - - `PINECONE_DEBUG_CURL`: When troubleshooting it can be very useful to run curl - commands against the control plane API to see exactly what data is being sent - and received without all the abstractions and transformations applied by the Python - SDK. If you set this environment variable to `true`, the Pinecone client will use - request parameters to print out an equivalent curl command that you can run yourself - or share with Pinecone support. **Be very careful with this option, as it will print out - your API key** which forms part of a required authentication header. The main use of - is to help evaluate whether a problem you are experiencing is due to the API's behavior - or the behavior of the SDK itself. - - ### Proxy configuration - - If your network setup requires you to interact with Pinecone via a proxy, you will need - to pass additional configuration using optional keyword parameters. These optional parameters - are forwarded to `urllib3`, which is the underlying library currently used by the Pinecone client to - make HTTP requests. You may find it helpful to refer to the - [urllib3 documentation on working with proxies](https://urllib3.readthedocs.io/en/stable/advanced-usage.html#http-and-https-proxies) - while troubleshooting these settings. - - Here is a basic example: - - ```python - from pinecone import Pinecone - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com' - ) - - pc.list_indexes() - ``` - - If your proxy requires authentication, you can pass those values in a header dictionary using the `proxy_headers` parameter. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password') - ) - - pc.list_indexes() - ``` - - ### Using proxies with self-signed certificates - - By default the Pinecone Python client will perform SSL certificate verification - using the CA bundle maintained by Mozilla in the [certifi](https://pypi.org/project/certifi/) package. - If your proxy server is using a self-signed certificate, you will need to pass the path to the certificate - in PEM format using the `ssl_ca_certs` parameter. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password'), - ssl_ca_certs='path/to/cert-bundle.pem' - ) - - pc.list_indexes() - ``` - - ### Disabling SSL verification - - If you would like to disable SSL verification, you can pass the `ssl_verify` - parameter with a value of `False`. We do not recommend going to production with SSL verification disabled. - - ```python - from pinecone import Pinecone - import urllib3 import make_headers - - pc = Pinecone( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - proxy_headers=make_headers(proxy_basic_auth='username:password'), - ssl_ca_certs='path/to/cert-bundle.pem', - ssl_verify=False - ) - - pc.list_indexes() - - ``` - """ - - pass - - @abstractmethod - def create_index( - self, - name: str, - spec: Union[Dict, ServerlessSpec, PodSpec], - dimension: Optional[int], - metric: Optional[Union[Metric, str]] = Metric.COSINE, - timeout: Optional[int] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - vector_type: Optional[Union[VectorType, str]] = VectorType.DENSE, - tags: Optional[Dict[str, str]] = None, - ) -> IndexModel: - """Creates a Pinecone index. - - :param name: The name of the index to create. Must be unique within your project and - cannot be changed once created. Allowed characters are lowercase letters, numbers, - and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. - :type name: str - :param metric: Type of similarity metric used in the vector index when querying, one of `{"cosine", "dotproduct", "euclidean"}`. - :type metric: str, optional - :param spec: A dictionary containing configurations describing how the index should be deployed. For serverless indexes, - specify region and cloud. For pod indexes, specify replicas, shards, pods, pod_type, metadata_config, and source_collection. - Alternatively, use the `ServerlessSpec` or `PodSpec` objects to specify these configurations. - :type spec: Dict - :param dimension: If you are creating an index with `vector_type="dense"` (which is the default), you need to specify `dimension` to indicate the size of your vectors. - This should match the dimension of the embeddings you will be inserting. For example, if you are using - OpenAI's CLIP model, you should use `dimension=1536`. Dimension is a required field when - creating an index with `vector_type="dense"` and should not be passed when `vector_type="sparse"`. - :type dimension: int - :type timeout: int, optional - :param timeout: Specify the number of seconds to wait until index gets ready. If None, wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :param deletion_protection: If enabled, the index cannot be deleted. If disabled, the index can be deleted. - :type deletion_protection: Optional[Literal["enabled", "disabled"]] - :param vector_type: The type of vectors to be stored in the index. One of `{"dense", "sparse"}`. - :type vector_type: str, optional - :param tags: Tags are key-value pairs you can attach to indexes to better understand, organize, and identify your resources. Some example use cases include tagging indexes with the name of the model that generated the embeddings, the date the index was created, or the purpose of the index. - :type tags: Optional[Dict[str, str]] - :return: A `IndexModel` instance containing a description of the index that was created. - - ### Creating a serverless index - - ```python - import os - from pinecone import ( - Pinecone, - ServerlessSpec, - CloudProvider, - AwsRegion, - Metric, - DeletionProtection, - VectorType - ) - - pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) - - pc.create_index( - name="my_index", - dimension=1536, - metric=Metric.COSINE, - spec=ServerlessSpec( - cloud=CloudProvider.AWS, - region=AwsRegion.US_WEST_2 - ), - deletion_protection=DeletionProtection.DISABLED, - vector_type=VectorType.DENSE, - tags={ - "model": "clip", - "app": "image-search", - "env": "testing" - } - ) - ``` - - ### Creating a pod index - - ```python - import os - from pinecone import ( - Pinecone, - PodSpec, - PodIndexEnvironment, - PodType, - Metric, - DeletionProtection, - VectorType - ) - - pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) - - pc.create_index( - name="my_index", - dimension=1536, - metric=Metric.COSINE, - spec=PodSpec( - environment=PodIndexEnvironment.US_EAST4_GCP, - pod_type=PodType.P1_X1 - ), - deletion_protection=DeletionProtection.DISABLED, - tags={ - "model": "clip", - "app": "image-search", - "env": "testing" - } - ) - ``` - """ - pass - - @abstractmethod - def create_index_for_model( - self, - name: str, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - embed: Union[IndexEmbed, CreateIndexForModelEmbedTypedDict], - tags: Optional[Dict[str, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - timeout: Optional[int] = None, - ) -> IndexModel: - """ - :param name: The name of the index to create. Must be unique within your project and - cannot be changed once created. Allowed characters are lowercase letters, numbers, - and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. - :type name: str - :param cloud: The cloud provider to use for the index. One of `{"aws", "gcp", "azure"}`. - :type cloud: str - :param region: The region to use for the index. Enum objects `AwsRegion`, `GcpRegion`, and `AzureRegion` are also available to help you quickly set these parameters, but may not be up to date as new regions become available. - :type region: str - :param embed: The embedding configuration for the index. This param accepts a dictionary or an instance of the `IndexEmbed` object. - :type embed: Union[Dict, IndexEmbed] - :param tags: Tags are key-value pairs you can attach to indexes to better understand, organize, and identify your resources. Some example use cases include tagging indexes with the name of the model that generated the embeddings, the date the index was created, or the purpose of the index. - :type tags: Optional[Dict[str, str]] - :param deletion_protection: If enabled, the index cannot be deleted. If disabled, the index can be deleted. This setting can be changed with `configure_index`. - :type deletion_protection: Optional[Literal["enabled", "disabled"]] - :type timeout: Optional[int] - :param timeout: Specify the number of seconds to wait until index is ready to receive data. If None, wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :return: A description of the index that was created. - :rtype: IndexModel - - This method is used to create a Serverless index that is configured for use with Pinecone's integrated inference models. - - The resulting index can be described, listed, configured, and deleted like any other Pinecone index with the `describe_index`, `list_indexes`, `configure_index`, and `delete_index` methods. - - After the model is created, you can upsert records into the index with the `upsert_records` method, and search your records with the `search` method. - - ```python - from pinecone import ( - Pinecone, - IndexEmbed, - CloudProvider, - AwsRegion, - EmbedModel, - Metric, - ) - - pc = Pinecone() - - if not pc.has_index("book-search"): - desc = await pc.create_index_for_model( - name="book-search", - cloud=CloudProvider.AWS, - region=AwsRegion.US_EAST_1, - embed=IndexEmbed( - model=EmbedModel.Multilingual_E5_Large, - metric=Metric.COSINE, - field_map={ - "text": "description", - }, - ) - ) - ``` - - To see the available cloud regions, see this [Pinecone documentation](https://docs.pinecone.io/troubleshooting/available-cloud-regions) page. - - See the [Model Gallery](https://docs.pinecone.io/models/overview) to learn about available models. - """ - pass - - @abstractmethod - def delete_index(self, name: str, timeout: Optional[int] = None): - """ - :param name: the name of the index. - :type name: str - :param timeout: Number of seconds to poll status checking whether the index has been deleted. If None, - wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :type timeout: int, optional - - Deletes a Pinecone index. - - Deleting an index is an irreversible operation. All data in the index will be lost. - When you use this command, a request is sent to the Pinecone control plane to delete - the index, but the termination is not synchronous because resources take a few moments to - be released. - - By default the `delete_index` method will block until polling of the `describe_index` method - shows that the delete operation has completed. If you prefer to return immediately and not - wait for the index to be deleted, you can pass `timeout=-1` to the method. - - After the delete request is submitted, polling `describe_index` will show that the index - transitions into a `Terminating` state before eventually resulting in a 404 after it has been removed. - - This operation can fail if the index is configured with `deletion_protection="enabled"`. - In this case, you will need to call `configure_index` to disable deletion protection before - you can delete the index. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - index_name = "my_index" - desc = pc.describe_index(name=index_name) - - if desc.deletion_protection == "enabled": - # If for some reason deletion protection is enabled, you will need to disable it first - # before you can delete the index. But use caution as this operation is not reversible - # and if somebody enabled deletion protection, they probably had a good reason. - pc.configure_index(name=index_name, deletion_protection="disabled") - - pc.delete_index(name=index_name) - ``` - """ - pass - - @abstractmethod - def list_indexes(self) -> IndexList: - """ - :return: Returns an `IndexList` object, which is iterable and contains a - list of `IndexModel` objects. The `IndexList` also has a convenience method `names()` - which returns a list of index names for situations where you just want to iterate over - all index names. - - Lists all indexes in your project. - - The results include a description of all indexes in your project, including the - index name, dimension, metric, status, and spec. - - If you simply want to check whether an index exists, see the `has_index()` convenience method. - - You can use the `list_indexes()` method to iterate over descriptions of every index in your project. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - for index in pc.list_indexes(): - print(index.name) - print(index.dimension) - print(index.metric) - print(index.status) - print(index.host) - print(index.spec) - ``` - """ - pass - - @abstractmethod - def describe_index(self, name: str) -> IndexModel: - """ - :param name: the name of the index to describe. - :return: Returns an `IndexModel` object - which gives access to properties such as the - index name, dimension, metric, host url, status, - and spec. - - Describes a Pinecone index. - - ### Getting your index host url - - In a real production situation, you probably want to - store the host url in an environment variable so you - don't have to call describe_index and re-fetch it - every time you want to use the index. But this example - shows how to get the value from the API using describe_index. - - ```python - from pinecone import Pinecone, Index - - pc = Pinecone() - - index_name="my_index" - description = pc.describe_index(name=index_name) - print(description) - # { - # "name": "my_index", - # "metric": "cosine", - # "host": "my_index-dojoi3u.svc.aped-4627-b74a.pinecone.io", - # "spec": { - # "serverless": { - # "cloud": "aws", - # "region": "us-east-1" - # } - # }, - # "status": { - # "ready": true, - # "state": "Ready" - # }, - # "vector_type": "dense", - # "dimension": 1024, - # "deletion_protection": "enabled", - # "tags": { - # "environment": "production" - # } - # } - - print(f"Your index is hosted at {description.host}") - - index = pc.Index(host=description.host) - index.upsert(vectors=[...]) - ``` - """ - pass - - @abstractmethod - def has_index(self, name: str) -> bool: - """ - :param name: The name of the index to check for existence. - :return: Returns `True` if the index exists, `False` otherwise. - - Checks if a Pinecone index exists. - - ```python - from pinecone import Pinecone, ServerlessSpec - - pc = Pinecone() - - index_name = "my_index" - if not pc.has_index(index_name): - print("Index does not exist, creating...") - pc.create_index( - name=index_name, - dimension=768, - metric="cosine", - spec=ServerlessSpec(cloud="aws", region="us-west-2") - ) - ``` - """ - pass - - @abstractmethod - def configure_index( - self, - name: str, - replicas: Optional[int] = None, - pod_type: Optional[Union[PodType, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = None, - tags: Optional[Dict[str, str]] = None, - ): - """ - :param: name: the name of the Index - :param: replicas: the desired number of replicas, lowest value is 0. - :param: pod_type: the new pod_type for the index. To learn more about the - available pod types, please see [Understanding Indexes](https://docs.pinecone.io/docs/indexes) - :param: deletion_protection: If set to 'enabled', the index cannot be deleted. If 'disabled', the index can be deleted. - :param: tags: A dictionary of tags to apply to the index. Tags are key-value pairs that can be used to organize and manage indexes. To remove a tag, set the value to "". Tags passed to configure_index will be merged with existing tags and any with the value empty string will be removed. - - This method is used to modify an index's configuration. It can be used to: - - - Scale a pod-based index horizontally using `replicas` - - Scale a pod-based index vertically using `pod_type` - - Enable or disable deletion protection using `deletion_protection` - - Add, change, or remove tags using `tags` - - ## Scaling pod-based indexes - - To scale your pod-based index, you pass a `replicas` and/or `pod_type` param to the `configure_index` method. `pod_type` may be a string or a value from the `PodType` enum. - - ```python - from pinecone import Pinecone, PodType - - pc = Pinecone() - pc.configure_index( - name="my_index", - replicas=2, - pod_type=PodType.P1_X2 - ) - ``` - - After providing these new configurations, you must call `describe_index` to see the status of the index as the changes are applied. - - ## Enabling or disabling deletion protection - - To enable or disable deletion protection, pass the `deletion_protection` parameter to the `configure_index` method. When deletion protection - is enabled, the index cannot be deleted with the `delete_index` method. - - ```python - from pinecone import Pinecone, DeletionProtection - - pc = Pinecone() - - # Enable deletion protection - pc.configure_index( - name="my_index", - deletion_protection=DeletionProtection.ENABLED - ) - - # Call describe_index to see the change was applied. - assert pc.describe_index("my_index").deletion_protection == "enabled" - - # Disable deletion protection - pc.configure_index( - name="my_index", - deletion_protection=DeletionProtection.DISABLED - ) - ``` - - ## Adding, changing, or removing tags - - To add, change, or remove tags, pass the `tags` parameter to the `configure_index` method. When tags are passed using `configure_index`, - they are merged with any existing tags already on the index. To remove a tag, set the value of the key to an empty string. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - # Add a tag - pc.configure_index(name="my_index", tags={"environment": "staging"}) - - # Change a tag - pc.configure_index(name="my_index", tags={"environment": "production"}) - - # Remove a tag - pc.configure_index(name="my_index", tags={"environment": ""}) - - # Call describe_index to view the tags are changed - print(pc.describe_index("my_index").tags) - ``` - """ - pass - - @abstractmethod - def create_collection(self, name: str, source: str): - """Create a collection from a pod-based index - - :param name: Name of the collection - :param source: Name of the source index - """ - pass - - @abstractmethod - def list_collections(self) -> CollectionList: - """List all collections - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - for collection in pc.list_collections(): - print(collection.name) - print(collection.source) - - # You can also iterate specifically over the collection - # names with the .names() helper. - collection_name="my_collection" - for collection_name in pc.list_collections().names(): - print(collection_name) - ``` - """ - pass - - @abstractmethod - def delete_collection(self, name: str) -> None: - """ - :param name: The name of the collection to delete. - - Deletes a collection. - - Deleting a collection is an irreversible operation. All data - in the collection will be lost. - - This method tells Pinecone you would like to delete a collection, - but it takes a few moments to complete the operation. Use the - `describe_collection()` method to confirm that the collection - has been deleted. - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - pc.delete_collection(name="my_collection") - ``` - """ - pass - - @abstractmethod - def describe_collection(self, name: str): - """Describes a collection. - :param: The name of the collection - :return: Description of the collection - - ```python - from pinecone import Pinecone - - pc = Pinecone() - - description = pc.describe_collection("my_collection") - print(description.name) - print(description.source) - print(description.status) - print(description.size) - ``` - """ - pass - - @abstractmethod - def Index(self, name: str = "", host: str = "", **kwargs): - """ - :param name: The name of the index to target. If you specify the name of the index, the client will - fetch the host url from the Pinecone control plane. - :param host: The host url of the index to target. If you specify the host url, the client will use - the host url directly without making any additional calls to the control plane. - :param pool_threads: The number of threads to use when making parallel requests by calling index methods with optional kwarg async_req=True, or using methods that make use of thread-based parallelism automatically such as query_namespaces(). - :param connection_pool_maxsize: The maximum number of connections to keep in the connection pool. - :return: An instance of the `Index` class. - - Target an index for data operations. - - ### Target an index by host url - - In production situations, you want to uspert or query your data as quickly - as possible. If you know in advance the host url of your index, you can - eliminate a round trip to the Pinecone control plane by specifying the - host of the index. If instead you pass the name of the index, the client - will need to make an additional call to api.pinecone.io to get the host url - before any data operations can take place. - - ```python - import os - from pinecone import Pinecone - - api_key = os.environ.get("PINECONE_API_KEY") - index_host = os.environ.get("PINECONE_INDEX_HOST") - - pc = Pinecone(api_key=api_key) - index = pc.Index(host=index_host) - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - - To find your host url, you can use the describe_index method to call api.pinecone.io. - The host url is returned in the response. Or, alternatively, the - host is displayed in the Pinecone web console. - - ```python - import os - from pinecone import Pinecone - - pc = Pinecone( - api_key=os.environ.get("PINECONE_API_KEY") - ) - - host = pc.describe_index('index-name').host - ``` - - ### Target an index by name (not recommended for production) - - For more casual usage, such as when you are playing and exploring with Pinecone - in a notebook setting, you can also target an index by name. If you use this - approach, the client may need to perform an extra call to the Pinecone control - plane to get the host url on your behalf to get the index host. - - The client will cache the index host for future use whenever it is seen, so you - will only incur the overhead of only one call. But this approach is not - recommended for production usage because it introduces an unnecessary runtime - dependency on api.pinecone.io. - - ```python - import os - from pinecone import Pinecone, ServerlessSpec - - api_key = os.environ.get("PINECONE_API_KEY") - - pc = Pinecone(api_key=api_key) - pc.create_index( - name='my_index', - dimension=1536, - metric='cosine', - spec=ServerlessSpec(cloud='aws', region='us-west-2') - ) - index = pc.Index('my_index') - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - """ - pass - - def IndexAsyncio(self, host: str, **kwargs): - """Build an asyncio-compatible Index object. - - :param host: The host url of the index to target. You can find this url in the Pinecone - web console or by calling describe_index method of `Pinecone` or `PineconeAsyncio`. - - :return: An instance of the `IndexAsyncio` class. - """ - pass diff --git a/pinecone/control/pinecone_interface_asyncio.py b/pinecone/control/pinecone_interface_asyncio.py deleted file mode 100644 index a732bce91..000000000 --- a/pinecone/control/pinecone_interface_asyncio.py +++ /dev/null @@ -1,926 +0,0 @@ -from abc import ABC, abstractmethod - -from typing import Optional, Dict, Union - - -from pinecone.config import Config - -from pinecone.core.openapi.db_control.api.manage_indexes_api import ManageIndexesApi - - -from pinecone.models import ( - ServerlessSpec, - PodSpec, - IndexList, - CollectionList, - IndexModel, - IndexEmbed, -) -from pinecone.enums import ( - Metric, - VectorType, - DeletionProtection, - PodType, - CloudProvider, - AwsRegion, - GcpRegion, - AzureRegion, -) -from .types import CreateIndexForModelEmbedTypedDict - - -class PineconeAsyncioDBControlInterface(ABC): - @abstractmethod - def __init__( - self, - api_key: Optional[str] = None, - host: Optional[str] = None, - proxy_url: Optional[str] = None, - proxy_headers: Optional[Dict[str, str]] = None, - ssl_ca_certs: Optional[str] = None, - ssl_verify: Optional[bool] = None, - config: Optional[Config] = None, - additional_headers: Optional[Dict[str, str]] = {}, - pool_threads: Optional[int] = 1, - index_api: Optional[ManageIndexesApi] = None, - **kwargs, - ): - """ - The `PineconeAsyncio` class is the main entry point for interacting with Pinecone using asyncio. - It is used to create, delete, and manage your indexes and collections. Except for needing to use - `async with` when instantiating the client and `await` when calling its methods, the functionality - provided by this class is extremely similar to the functionality of the `Pinecone` class. - - :param api_key: The API key to use for authentication. If not passed via kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - :type api_key: str, optional - :param host: The control plane host to connect to. - :type host: str, optional - :param proxy_url: The URL of the proxy to use for the connection. Default: `None` - :type proxy_url: str, optional - :param proxy_headers: Additional headers to pass to the proxy. Use this if your proxy setup requires authentication. Default: `{}` - :type proxy_headers: Dict[str, str], optional - :param ssl_ca_certs: The path to the SSL CA certificate bundle to use for the connection. This path should point to a file in PEM format. Default: `None` - :type ssl_ca_certs: str, optional - :param ssl_verify: SSL verification is performed by default, but can be disabled using the boolean flag. Default: `True` - :type ssl_verify: bool, optional - :param config: A `pinecone.config.Config` object. If passed, the `api_key` and `host` parameters will be ignored. - :type config: pinecone.config.Config, optional - :param additional_headers: Additional headers to pass to the API. Default: `{}` - :type additional_headers: Dict[str, str], optional - - - ### Managing the async context - - The `PineconeAsyncio` class relies on an underlying `aiohttp` `ClientSession` to make asynchronous HTTP requests. To ensure that the session is properly closed, you - should use the `async with` syntax when creating a `PineconeAsyncio` object. This will ensure that the session is properly closed when the context is exited. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio(api_key='YOUR_API_KEY') as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - As an alternative, if you prefer to avoid code with a nested appearance and are willing to manage cleanup yourself, you can await the `close()` method to close the session when you are done. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - pc = PineconeAsyncio(api_key='YOUR_API_KEY') - - # Do async things - index_list = await pc.list_indexes() - - # You're responsible for calling this yourself - await pc.close() - - asyncio.run(main()) - ``` - - Failing to do this may result in error messages appearing from the underlyling aiohttp library. - - ### Configuration with environment variables - - If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Configuration with keyword arguments - - If you prefer being more explicit in your code, you can also pass the API as - - ### Configuration with environment variables - - If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Configuration with keyword arguments - - If you prefer being more explicit in your code, you can also pass the API as - - - - ### Configuration with environment variables - - If you instantiate the Pinecone client with no arguments, it will attempt to read the API key from the environment variable `PINECONE_API_KEY`. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Configuration with keyword arguments - - If you prefer being more explicit in your code, you can also pass the API as a keyword argument. - - ```python - import os - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Environment variables - - The Pinecone client supports the following environment variables: - - - `PINECONE_API_KEY`: The API key to use for authentication. If not passed via - kwarg, the API key will be read from the environment variable `PINECONE_API_KEY`. - - ### Proxy configuration - - If your network setup requires you to interact with Pinecone via a proxy, you will need - to pass additional configuration using optional keyword parameters. These optional parameters - are used to configure an SSL context and passed to `aiohttp`, which is the underlying library - currently used by the PineconeAsyncio client to make HTTP requests. - - Here is a basic example: - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com' - ) as pc: - # Do async things - index_list = await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Using proxies with self-signed certificates - - By default the Pinecone Python client will perform SSL certificate verification - using the CA bundle maintained by Mozilla in the [certifi](https://pypi.org/project/certifi/) package. - If your proxy server is using a self-signed certificate, you will need to pass the path to the certificate - in PEM format using the `ssl_ca_certs` parameter. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio( - api_key='YOUR_API_KEY', - proxy_url='https://your-proxy.com', - ssl_ca_certs='path/to/cert-bundle.pem' - ) as pc: - # Do async things - await pc.list_indexes() - - asyncio.run(main()) - ``` - - ### Disabling SSL verification - - If you would like to disable SSL verification, you can pass the `ssl_verify` - parameter with a value of `False`. We do not recommend going to production with SSL verification disabled - but there are situations where this is useful such as testing with Pinecone Local running in a docker - container. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio( - api_key='YOUR_API_KEY', - ssl_verify=False - ) as pc: - if not await pc.has_index('my_index'): - await pc.create_index( - name='my_index', - dimension=1536, - metric='cosine', - spec=ServerlessSpec(cloud='aws', region='us-west-2') - ) - - asyncio.run(main()) - ``` - - ### Passing additional headers - - If you need to pass additional headers with each request to the Pinecone API, you can do so using the - `additional_headers` parameter. This is primarily for internal testing and end-users shouldn't need to - do this unless specifically instructed to do so. - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio( - api_key='YOUR_API_KEY', - host='https://api-staging.pinecone.io', - additional_headers={'X-My-Header': 'my-value'} - ) as pc: - # Do async things - await pc.list_indexes() - - asyncio.run(main()) - ``` - """ - - pass - - @abstractmethod - async def create_index( - self, - name: str, - spec: Union[Dict, ServerlessSpec, PodSpec], - dimension: Optional[int], - metric: Optional[Union[Metric, str]] = Metric.COSINE, - timeout: Optional[int] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - vector_type: Optional[Union[VectorType, str]] = VectorType.DENSE, - tags: Optional[Dict[str, str]] = None, - ): - """Creates a Pinecone index. - - :param name: The name of the index to create. Must be unique within your project and - cannot be changed once created. Allowed characters are lowercase letters, numbers, - and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. - :type name: str - :param metric: Type of similarity metric used in the vector index when querying, one of `{"cosine", "dotproduct", "euclidean"}`. - :type metric: str, optional - :param spec: A dictionary containing configurations describing how the index should be deployed. For serverless indexes, - specify region and cloud. For pod indexes, specify replicas, shards, pods, pod_type, metadata_config, and source_collection. - Alternatively, use the `ServerlessSpec` or `PodSpec` objects to specify these configurations. - :type spec: Dict - :param dimension: If you are creating an index with `vector_type="dense"` (which is the default), you need to specify `dimension` to indicate the size of your vectors. - This should match the dimension of the embeddings you will be inserting. For example, if you are using - OpenAI's CLIP model, you should use `dimension=1536`. Dimension is a required field when - creating an index with `vector_type="dense"` and should not be passed when `vector_type="sparse"`. - :type dimension: int - :type timeout: int, optional - :param timeout: Specify the number of seconds to wait until index gets ready. If None, wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :param deletion_protection: If enabled, the index cannot be deleted. If disabled, the index can be deleted. - :type deletion_protection: Optional[Literal["enabled", "disabled"]] - :param vector_type: The type of vectors to be stored in the index. One of `{"dense", "sparse"}`. - :type vector_type: str, optional - :param tags: Tags are key-value pairs you can attach to indexes to better understand, organize, and identify your resources. Some example use cases include tagging indexes with the name of the model that generated the embeddings, the date the index was created, or the purpose of the index. - :type tags: Optional[Dict[str, str]] - :return: A `IndexModel` instance containing a description of the index that was created. - - ### Creating a serverless index - - ```python - import os - import asyncio - - from pinecone import ( - PineconeAsyncio, - ServerlessSpec, - CloudProvider, - AwsRegion, - Metric, - DeletionProtection, - VectorType - ) - - async def main(): - async with PineconeAsyncio(api_key=os.environ.get("PINECONE_API_KEY")) as pc: - await pc.create_index( - name="my_index", - dimension=1536, - metric=Metric.COSINE, - spec=ServerlessSpec( - cloud=CloudProvider.AWS, - region=AwsRegion.US_WEST_2 - ), - deletion_protection=DeletionProtection.DISABLED, - vector_type=VectorType.DENSE, - tags={ - "model": "clip", - "app": "image-search", - "env": "testing" - } - ) - - asyncio.run(main()) - ``` - - ### Creating a pod index - - ```python - import os - import asyncio - - from pinecone import ( - Pinecone, - PodSpec, - PodIndexEnvironment, - PodType, - Metric, - DeletionProtection, - VectorType - ) - - async def main(): - async with Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) as pc: - await pc.create_index( - name="my_index", - dimension=1536, - metric=Metric.COSINE, - spec=PodSpec( - environment=PodIndexEnvironment.US_EAST4_GCP, - pod_type=PodType.P1_X1 - ), - deletion_protection=DeletionProtection.DISABLED, - tags={ - "model": "clip", - "app": "image-search", - "env": "testing" - } - ) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def create_index_for_model( - self, - name: str, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - embed: Union[IndexEmbed, CreateIndexForModelEmbedTypedDict], - tags: Optional[Dict[str, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - timeout: Optional[int] = None, - ) -> IndexModel: - """ - :param name: The name of the index to create. Must be unique within your project and - cannot be changed once created. Allowed characters are lowercase letters, numbers, - and hyphens and the name may not begin or end with hyphens. Maximum length is 45 characters. - :type name: str - :param cloud: The cloud provider to use for the index. One of `{"aws", "gcp", "azure"}`. - :type cloud: str - :param region: The region to use for the index. Enum objects `AwsRegion`, `GcpRegion`, and `AzureRegion` are also available to help you quickly set these parameters, but may not be up to date as new regions become available. - :type region: str - :param embed: The embedding configuration for the index. This param accepts a dictionary or an instance of the `IndexEmbed` object. - :type embed: Union[Dict, IndexEmbed] - :param tags: Tags are key-value pairs you can attach to indexes to better understand, organize, and identify your resources. Some example use cases include tagging indexes with the name of the model that generated the embeddings, the date the index was created, or the purpose of the index. - :type tags: Optional[Dict[str, str]] - :param deletion_protection: If enabled, the index cannot be deleted. If disabled, the index can be deleted. This setting can be changed with `configure_index`. - :type deletion_protection: Optional[Literal["enabled", "disabled"]] - :type timeout: Optional[int] - :param timeout: Specify the number of seconds to wait until index is ready to receive data. If None, wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :return: A description of the index that was created. - :rtype: IndexModel - - This method is used to create a Serverless index that is configured for use with Pinecone's integrated inference models. - - The resulting index can be described, listed, configured, and deleted like any other Pinecone index with the `describe_index`, `list_indexes`, `configure_index`, and `delete_index` methods. - - After the model is created, you can upsert records into the index with the `upsert_records` method, and search your records with the `search` method. - - ```python - import asyncio - - from pinecone import ( - PineconeAsyncio, - IndexEmbed, - CloudProvider, - AwsRegion, - EmbedModel, - Metric, - ) - - async def main(): - async with PineconeAsyncio() as pc: - if not await pc.has_index("book-search"): - desc = await pc.create_index_for_model( - name="book-search", - cloud=CloudProvider.AWS, - region=AwsRegion.US_EAST_1, - embed=IndexEmbed( - model=EmbedModel.Multilingual_E5_Large, - metric=Metric.COSINE, - field_map={ - "text": "description", - }, - ) - ) - - asyncio.run(main()) - ``` - - To see the available cloud regions, see this [Pinecone documentation](https://docs.pinecone.io/troubleshooting/available-cloud-regions) page. - - See the [Model Gallery](https://docs.pinecone.io/models/overview) to learn about available models. - """ - pass - - @abstractmethod - async def delete_index(self, name: str, timeout: Optional[int] = None): - """ - :param name: the name of the index. - :type name: str - :param timeout: Number of seconds to poll status checking whether the index has been deleted. If None, - wait indefinitely; if >=0, time out after this many seconds; - if -1, return immediately and do not wait. - :type timeout: int, optional - - Deletes a Pinecone index. - - Deleting an index is an irreversible operation. All data in the index will be lost. - When you use this command, a request is sent to the Pinecone control plane to delete - the index, but the termination is not synchronous because resources take a few moments to - be released. - - By default the `delete_index` method will block until polling of the `describe_index` method - shows that the delete operation has completed. If you prefer to return immediately and not - wait for the index to be deleted, you can pass `timeout=-1` to the method. - - After the delete request is submitted, polling `describe_index` will show that the index - transitions into a `Terminating` state before eventually resulting in a 404 after it has been removed. - - This operation can fail if the index is configured with `deletion_protection="enabled"`. - In this case, you will need to call `configure_index` to disable deletion protection before - you can delete the index. - - ```python - import asyncio - - from pinecone import PineconeAsyncio - - async def main(): - pc = PineconeAsyncio() - - index_name = "my_index" - desc = await pc.describe_index(name=index_name) - - if desc.deletion_protection == "enabled": - # If for some reason deletion protection is enabled, you will need to disable it first - # before you can delete the index. But use caution as this operation is not reversible - # and if somebody enabled deletion protection, they probably had a good reason. - await pc.configure_index(name=index_name, deletion_protection="disabled") - - await pc.delete_index(name=index_name) - await pc.close() - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def list_indexes(self) -> IndexList: - """ - :return: Returns an `IndexList` object, which is iterable and contains a - list of `IndexModel` objects. The `IndexList` also has a convenience method `names()` - which returns a list of index names for situations where you just want to iterate over - all index names. - - Lists all indexes in your project. - - The results include a description of all indexes in your project, including the - index name, dimension, metric, status, and spec. - - If you simply want to check whether an index exists, see the `has_index()` convenience method. - - You can use the `list_indexes()` method to iterate over descriptions of every index in your project. - - ```python - import asyncio - - from pinecone import PineconeAsyncio - - async def main(): - pc = PineconeAsyncio() - - available_indexes = await pc.list_indexes() - for index in available_indexes: - print(index.name) - print(index.dimension) - print(index.metric) - print(index.status) - print(index.host) - print(index.spec) - - await pc.close() - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def describe_index(self, name: str) -> IndexModel: - """ - :param name: the name of the index to describe. - :return: Returns an `IndexModel` object - which gives access to properties such as the - index name, dimension, metric, host url, status, - and spec. - - Describes a Pinecone index. - - ### Getting your index host url - - In a real production situation, you probably want to - store the host url in an environment variable so you - don't have to call describe_index and re-fetch it - every time you want to use the index. But this example - shows how to get the value from the API using describe_index. - - ```python - import asyncio - from pinecone import Pinecone, PineconeAsyncio, Index - - async def main(): - pc = PineconeAsyncio() - - index_name="my_index" - description = await pc.describe_index(name=index_name) - print(description) - # { - # "name": "my_index", - # "metric": "cosine", - # "host": "my_index-dojoi3u.svc.aped-4627-b74a.pinecone.io", - # "spec": { - # "serverless": { - # "cloud": "aws", - # "region": "us-east-1" - # } - # }, - # "status": { - # "ready": true, - # "state": "Ready" - # }, - # "vector_type": "dense", - # "dimension": 1024, - # "deletion_protection": "enabled", - # "tags": { - # "environment": "production" - # } - # } - - print(f"Your index is hosted at {description.host}") - await pc.close() - - async with Pinecone().IndexAsyncio(host=description.host) as idx: - await idx.upsert(vectors=[...]) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def has_index(self, name: str) -> bool: - """ - :param name: The name of the index to check for existence. - :return: Returns `True` if the index exists, `False` otherwise. - - Checks if a Pinecone index exists. - - ```python - import asyncio - from pinecone import PineconeAsyncio, ServerlessSpec - - async def main(): - async with PineconeAsyncio() as pc: - index_name = "my_index" - if not await pc.has_index(index_name): - print("Index does not exist, creating...") - pc.create_index( - name=index_name, - dimension=768, - metric="cosine", - spec=ServerlessSpec(cloud="aws", region="us-west-2") - ) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def configure_index( - self, - name: str, - replicas: Optional[int] = None, - pod_type: Optional[Union[PodType, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = None, - tags: Optional[Dict[str, str]] = None, - ): - """ - :param: name: the name of the Index - :param: replicas: the desired number of replicas, lowest value is 0. - :param: pod_type: the new pod_type for the index. To learn more about the - available pod types, please see [Understanding Indexes](https://docs.pinecone.io/docs/indexes) - :param: deletion_protection: If set to 'enabled', the index cannot be deleted. If 'disabled', the index can be deleted. - :param: tags: A dictionary of tags to apply to the index. Tags are key-value pairs that can be used to organize and manage indexes. To remove a tag, set the value to "". Tags passed to configure_index will be merged with existing tags and any with the value empty string will be removed. - - This method is used to modify an index's configuration. It can be used to: - - - Scale a pod-based index horizontally using `replicas` - - Scale a pod-based index vertically using `pod_type` - - Enable or disable deletion protection using `deletion_protection` - - Add, change, or remove tags using `tags` - - ## Scaling pod-based indexes - - To scale your pod-based index, you pass a `replicas` and/or `pod_type` param to the `configure_index` method. `pod_type` may be a string or a value from the `PodType` enum. - - ```python - import asyncio - from pinecone import PineconeAsyncio, PodType - - async def main(): - async with PineconeAsyncio() as pc: - await pc.configure_index( - name="my_index", - replicas=2, - pod_type=PodType.P1_X2 - ) - - asyncio.run(main()) - ``` - - After providing these new configurations, you must call `describe_index` to see the status of the index as the changes are applied. - - ## Enabling or disabling deletion protection - - To enable or disable deletion protection, pass the `deletion_protection` parameter to the `configure_index` method. When deletion protection - is enabled, the index cannot be deleted with the `delete_index` method. - - ```python - import asyncio - from pinecone import PineconeAsyncio, DeletionProtection - - async def main(): - async with PineconeAsyncio() as pc: - # Enable deletion protection - await pc.configure_index( - name="my_index", - deletion_protection=DeletionProtection.ENABLED - ) - - # Call describe_index to see the change was applied. - desc = await pc.describe_index("my_index") - assert desc.deletion_protection == "enabled" - - # Disable deletion protection - await pc.configure_index( - name="my_index", - deletion_protection=DeletionProtection.DISABLED - ) - - asyncio.run(main()) - ``` - - ## Adding, changing, or removing tags - - To add, change, or remove tags, pass the `tags` parameter to the `configure_index` method. When tags are passed using `configure_index`, - they are merged with any existing tags already on the index. To remove a tag, set the value of the key to an empty string. - - ```python - import asyncio - - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - # Add a tag - await pc.configure_index(name="my_index", tags={"environment": "staging"}) - - # Change a tag - await pc.configure_index(name="my_index", tags={"environment": "production"}) - - # Remove a tag - await pc.configure_index(name="my_index", tags={"environment": ""}) - - # Call describe_index to view the tags are changed - await pc.describe_index("my_index") - print(desc.tags) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def create_collection(self, name: str, source: str): - """Create a collection from a pod-based index - - :param name: Name of the collection - :param source: Name of the source index - """ - pass - - @abstractmethod - async def list_collections(self) -> CollectionList: - """List all collections - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - pc = PineconeAsyncio() - - collections = await pc.list_collections() - for collection in collections: - print(collection.name) - print(collection.source) - - # You can also iterate specifically over - # a list of collection names by calling - # the .names() helper. - collection_name = "my_collection" - collections = await pc.list_collections() - if collection_name in collections.names(): - print('Collection exists') - - await pc.close() - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def delete_collection(self, name: str): - """Describes a collection. - :param: The name of the collection - :return: Description of the collection - - ```python - import asyncio - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio() as pc: - - description = await pc.describe_collection("my_collection") - print(description.name) - print(description.source) - print(description.status) - print(description.size) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def describe_collection(self, name: str): - """Describes a collection. - :param: The name of the collection - :return: Description of the collection - - ```python - import asyncio - from pinecone import PineconeAsyncio - - - async def main(): - async with PineconeAsyncio() as pc: - description = await pc.describe_collection("my_collection") - print(description.name) - print(description.source) - print(description.status) - print(description.size) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - def IndexAsyncio(self, host, **kwargs): - """ - Build an asyncio-compatible client for index data operations. - - :param host: The host url of the index. - - ```python - import os - import asyncio - - from pinecone import PineconeAsyncio - - api_key = os.environ.get("PINECONE_API_KEY") - index_host = os.environ.get("PINECONE_INDEX_HOST") - - async def main(): - async with Pinecone(api_key=api_key) as pc: - async with pc.Index(host=index_host) as idx: - # Now you're ready to perform data operations - await index.query(vector=[...], top_k=10) - - asyncio.run(main()) - ``` - - To find your host url, you can use the `describe_index`. Or, alternatively, the - host is displayed in the Pinecone web console. - - ```python - import os - import asyncio - - from pinecone import PineconeAsyncio - - async def main(): - async with PineconeAsyncio( - api_key=os.environ.get("PINECONE_API_KEY") - ) as pc: - host = await pc.describe_index('index-name').host - - asyncio.run(main()) - ``` - - ## Alternative setup - - Like instances of the `PineconeAsyncio` class, instances of `IndexAsyncio` have async context that - needs to be cleaned up when you are done with it in order to avoid error messages about unclosed session from - aiohttp. Nesting these in code is a bit cumbersome, so if you are only planning to do data operations you - may prefer to setup the `IndexAsyncio` object via the `Pinecone` class which will avoid creating an outer async context. - - ```python - import os - import asyncio - from pinecone import Pinecone - - api_key = os.environ.get("PINECONE_API_KEY") - - async def main(): - pc = Pinecone(api_key=api_key) # sync client, so no async context to worry about - - async with pc.AsyncioIndex(host='your_index_host') as idx: - # Now you're ready to perform data operations - await idx.query(vector=[...], top_k=10) - - ``` - """ - pass diff --git a/pinecone/control/repr_overrides.py b/pinecone/control/repr_overrides.py deleted file mode 100644 index 98e4b4d4e..000000000 --- a/pinecone/control/repr_overrides.py +++ /dev/null @@ -1,16 +0,0 @@ -from pinecone.utils import install_json_repr_override -from pinecone.models.index_model import IndexModel -from pinecone.core.openapi.db_control.models import CollectionModel - - -def install_repr_overrides(): - """ - The generator code uses pprint.pformat to format the repr output - which looks really poor when printing a list of large objects - in a notebook setting. We override it here for a few select models - instead of modifying the generator code because the more compact output - from pprint.pformat seems better for data plane objects such as lists of - query results. - """ - for model in [IndexModel, CollectionModel]: - install_json_repr_override(model) diff --git a/pinecone/control/request_factory.py b/pinecone/control/request_factory.py deleted file mode 100644 index d4d0ce630..000000000 --- a/pinecone/control/request_factory.py +++ /dev/null @@ -1,251 +0,0 @@ -import logging -from typing import Optional, Dict, Any, Union -from enum import Enum - - -from pinecone.utils import convert_enum_to_string -from pinecone.core.openapi.db_control.models import ( - CreateCollectionRequest, - CreateIndexForModelRequest, - CreateIndexForModelRequestEmbed, - CreateIndexRequest, - ConfigureIndexRequest, - ConfigureIndexRequestSpec, - ConfigureIndexRequestSpecPod, - DeletionProtection as DeletionProtectionModel, - IndexSpec, - IndexTags, - ServerlessSpec as ServerlessSpecModel, - PodSpec as PodSpecModel, - PodSpecMetadataConfig, -) -from pinecone.models import ServerlessSpec, PodSpec, IndexModel, IndexEmbed -from pinecone.utils import parse_non_empty_args - -from pinecone.enums import ( - Metric, - VectorType, - DeletionProtection, - PodType, - CloudProvider, - AwsRegion, - GcpRegion, - AzureRegion, -) -from .types import CreateIndexForModelEmbedTypedDict - - -logger = logging.getLogger(__name__) -""" @private """ - - -class PineconeDBControlRequestFactory: - """ - @private - - This class facilitates translating user inputs into request objects. - """ - - @staticmethod - def __parse_tags(tags: Optional[Dict[str, str]]) -> IndexTags: - if tags is None: - return IndexTags() - else: - return IndexTags(**tags) - - @staticmethod - def __parse_deletion_protection( - deletion_protection: Union[DeletionProtection, str], - ) -> DeletionProtectionModel: - deletion_protection = convert_enum_to_string(deletion_protection) - if deletion_protection in ["enabled", "disabled"]: - return DeletionProtectionModel(deletion_protection) - else: - raise ValueError("deletion_protection must be either 'enabled' or 'disabled'") - - @staticmethod - def __parse_index_spec(spec: Union[Dict, ServerlessSpec, PodSpec]) -> IndexSpec: - if isinstance(spec, dict): - if "serverless" in spec: - spec["serverless"]["cloud"] = convert_enum_to_string(spec["serverless"]["cloud"]) - spec["serverless"]["region"] = convert_enum_to_string(spec["serverless"]["region"]) - - index_spec = IndexSpec(serverless=ServerlessSpecModel(**spec["serverless"])) - elif "pod" in spec: - spec["pod"]["environment"] = convert_enum_to_string(spec["pod"]["environment"]) - args_dict = parse_non_empty_args( - [ - ("environment", spec["pod"].get("environment")), - ("metadata_config", spec["pod"].get("metadata_config")), - ("replicas", spec["pod"].get("replicas")), - ("shards", spec["pod"].get("shards")), - ("pods", spec["pod"].get("pods")), - ("source_collection", spec["pod"].get("source_collection")), - ] - ) - if args_dict.get("metadata_config"): - args_dict["metadata_config"] = PodSpecMetadataConfig( - indexed=args_dict["metadata_config"].get("indexed", None) - ) - index_spec = IndexSpec(pod=PodSpecModel(**args_dict)) - else: - raise ValueError("spec must contain either 'serverless' or 'pod' key") - elif isinstance(spec, ServerlessSpec): - index_spec = IndexSpec( - serverless=ServerlessSpecModel(cloud=spec.cloud, region=spec.region) - ) - elif isinstance(spec, PodSpec): - args_dict = parse_non_empty_args( - [ - ("replicas", spec.replicas), - ("shards", spec.shards), - ("pods", spec.pods), - ("source_collection", spec.source_collection), - ] - ) - if spec.metadata_config: - args_dict["metadata_config"] = PodSpecMetadataConfig( - indexed=spec.metadata_config.get("indexed", None) - ) - - index_spec = IndexSpec( - pod=PodSpecModel(environment=spec.environment, pod_type=spec.pod_type, **args_dict) - ) - else: - raise TypeError("spec must be of type dict, ServerlessSpec, or PodSpec") - - return index_spec - - @staticmethod - def create_index_request( - name: str, - spec: Union[Dict, ServerlessSpec, PodSpec], - dimension: Optional[int] = None, - metric: Optional[Union[Metric, str]] = Metric.COSINE, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - vector_type: Optional[Union[VectorType, str]] = VectorType.DENSE, - tags: Optional[Dict[str, str]] = None, - ) -> CreateIndexRequest: - if metric is not None: - metric = convert_enum_to_string(metric) - if vector_type is not None: - vector_type = convert_enum_to_string(vector_type) - if deletion_protection is not None: - dp = PineconeDBControlRequestFactory.__parse_deletion_protection(deletion_protection) - else: - dp = None - - tags_obj = PineconeDBControlRequestFactory.__parse_tags(tags) - index_spec = PineconeDBControlRequestFactory.__parse_index_spec(spec) - - if vector_type == VectorType.SPARSE.value and dimension is not None: - raise ValueError("dimension should not be specified for sparse indexes") - - args = parse_non_empty_args( - [ - ("name", name), - ("dimension", dimension), - ("metric", metric), - ("spec", index_spec), - ("deletion_protection", dp), - ("vector_type", vector_type), - ("tags", tags_obj), - ] - ) - - return CreateIndexRequest(**args) - - @staticmethod - def create_index_for_model_request( - name: str, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - embed: Union[IndexEmbed, CreateIndexForModelEmbedTypedDict], - tags: Optional[Dict[str, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = DeletionProtection.DISABLED, - ) -> CreateIndexForModelRequest: - cloud = convert_enum_to_string(cloud) - region = convert_enum_to_string(region) - if deletion_protection is not None: - dp = PineconeDBControlRequestFactory.__parse_deletion_protection(deletion_protection) - else: - dp = None - tags_obj = PineconeDBControlRequestFactory.__parse_tags(tags) - - if isinstance(embed, IndexEmbed): - parsed_embed = embed.as_dict() - else: - # if dict, we need to parse enum values, if any, to string - # and verify required fields are present - required_fields = ["model", "field_map"] - for field in required_fields: - if field not in embed: - raise ValueError(f"{field} is required in embed") - parsed_embed = {} - for key, value in embed.items(): - if isinstance(value, Enum): - parsed_embed[key] = convert_enum_to_string(value) - else: - parsed_embed[key] = value - - args = parse_non_empty_args( - [ - ("name", name), - ("cloud", cloud), - ("region", region), - ("embed", CreateIndexForModelRequestEmbed(**parsed_embed)), - ("deletion_protection", dp), - ("tags", tags_obj), - ] - ) - - return CreateIndexForModelRequest(**args) - - @staticmethod - def configure_index_request( - description: IndexModel, - replicas: Optional[int] = None, - pod_type: Optional[Union[PodType, str]] = None, - deletion_protection: Optional[Union[DeletionProtection, str]] = None, - tags: Optional[Dict[str, str]] = None, - ): - if deletion_protection is None: - dp = DeletionProtectionModel(description.deletion_protection) - elif isinstance(deletion_protection, DeletionProtection): - dp = DeletionProtectionModel(deletion_protection.value) - elif deletion_protection in ["enabled", "disabled"]: - dp = DeletionProtectionModel(deletion_protection) - else: - raise ValueError("deletion_protection must be either 'enabled' or 'disabled'") - - fetched_tags = description.tags - if fetched_tags is None: - starting_tags = {} - else: - starting_tags = fetched_tags.to_dict() - - if tags is None: - # Do not modify tags if none are provided - tags = starting_tags - else: - # Merge existing tags with new tags - tags = {**starting_tags, **tags} - - pod_config_args: Dict[str, Any] = {} - if pod_type: - new_pod_type = convert_enum_to_string(pod_type) - pod_config_args.update(pod_type=new_pod_type) - if replicas: - pod_config_args.update(replicas=replicas) - - if pod_config_args != {}: - spec = ConfigureIndexRequestSpec(pod=ConfigureIndexRequestSpecPod(**pod_config_args)) - req = ConfigureIndexRequest(deletion_protection=dp, spec=spec, tags=IndexTags(**tags)) - else: - req = ConfigureIndexRequest(deletion_protection=dp, tags=IndexTags(**tags)) - - return req - - @staticmethod - def create_collection_request(name: str, source: str) -> CreateCollectionRequest: - return CreateCollectionRequest(name=name, source=source) diff --git a/pinecone/control/types/__init__.py b/pinecone/control/types/__init__.py deleted file mode 100644 index 12d16270d..000000000 --- a/pinecone/control/types/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .create_index_for_model_embed import CreateIndexForModelEmbedTypedDict diff --git a/pinecone/control/types/create_index_for_model_embed.py b/pinecone/control/types/create_index_for_model_embed.py deleted file mode 100644 index 123474a0a..000000000 --- a/pinecone/control/types/create_index_for_model_embed.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import TypedDict, Dict, Union -from ...enums import Metric -from ...data.features.inference import EmbedModel - - -class CreateIndexForModelEmbedTypedDict(TypedDict): - model: Union[EmbedModel, str] - field_map: Dict - metric: Union[Metric, str] - read_parameters: Dict - write_parameters: Dict diff --git a/pinecone/core/__init__.py b/pinecone/core/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/core/grpc/protos/db_data_2025_01_pb2.py b/pinecone/core/grpc/protos/db_data_2025_01_pb2.py deleted file mode 100644 index ab0491f8c..000000000 --- a/pinecone/core/grpc/protos/db_data_2025_01_pb2.py +++ /dev/null @@ -1,130 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# NO CHECKED-IN PROTOBUF GENCODE -# source: db_data_2025-01.proto -# Protobuf Python Version: 5.29.0 -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import descriptor_pool as _descriptor_pool -from google.protobuf import runtime_version as _runtime_version -from google.protobuf import symbol_database as _symbol_database -from google.protobuf.internal import builder as _builder -_runtime_version.ValidateProtobufRuntimeVersion( - _runtime_version.Domain.PUBLIC, - 5, - 29, - 0, - '', - 'db_data_2025-01.proto' -) -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 - - -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x64\x62_data_2025-01.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\"J\n\x0cSparseValues\x12\x1d\n\x07indices\x18\x01 \x03(\rB\x03\xe0\x41\x02R\x07indices\x12\x1b\n\x06values\x18\x02 \x03(\x02\x42\x03\xe0\x41\x02R\x06values\"\x9e\x01\n\x06Vector\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x16\n\x06values\x18\x02 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x04 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x33\n\x08metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x08metadata\"\xba\x01\n\x0cScoredVector\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x14\n\x05score\x18\x02 \x01(\x02R\x05score\x12\x16\n\x06values\x18\x03 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x33\n\x08metadata\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x08metadata\"\xa1\x01\n\x0cRequestUnion\x12(\n\x06upsert\x18\x01 \x01(\x0b\x32\x0e.UpsertRequestH\x00R\x06upsert\x12(\n\x06\x64\x65lete\x18\x02 \x01(\x0b\x32\x0e.DeleteRequestH\x00R\x06\x64\x65lete\x12(\n\x06update\x18\x03 \x01(\x0b\x32\x0e.UpdateRequestH\x00R\x06updateB\x13\n\x11RequestUnionInner\"U\n\rUpsertRequest\x12&\n\x07vectors\x18\x01 \x03(\x0b\x32\x07.VectorB\x03\xe0\x41\x02R\x07vectors\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"7\n\x0eUpsertResponse\x12%\n\x0eupserted_count\x18\x01 \x01(\rR\rupsertedCount\"\x8f\x01\n\rDeleteRequest\x12\x10\n\x03ids\x18\x01 \x03(\tR\x03ids\x12\x1d\n\ndelete_all\x18\x02 \x01(\x08R\tdeleteAll\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12/\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"\x10\n\x0e\x44\x65leteResponse\"C\n\x0c\x46\x65tchRequest\x12\x15\n\x03ids\x18\x01 \x03(\tB\x03\xe0\x41\x02R\x03ids\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"\xd6\x01\n\rFetchResponse\x12\x35\n\x07vectors\x18\x01 \x03(\x0b\x32\x1b.FetchResponse.VectorsEntryR\x07vectors\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x03 \x01(\x0b\x32\x06.UsageH\x00R\x05usage\x88\x01\x01\x1a\x43\n\x0cVectorsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x1d\n\x05value\x18\x02 \x01(\x0b\x32\x07.VectorR\x05value:\x02\x38\x01\x42\x08\n\x06_usage\"\xbd\x01\n\x0bListRequest\x12\x1b\n\x06prefix\x18\x01 \x01(\tH\x00R\x06prefix\x88\x01\x01\x12\x19\n\x05limit\x18\x02 \x01(\rH\x01R\x05limit\x88\x01\x01\x12.\n\x10pagination_token\x18\x03 \x01(\tH\x02R\x0fpaginationToken\x88\x01\x01\x12\x1c\n\tnamespace\x18\x04 \x01(\tR\tnamespaceB\t\n\x07_prefixB\x08\n\x06_limitB\x13\n\x11_pagination_token\" \n\nPagination\x12\x12\n\x04next\x18\x01 \x01(\tR\x04next\"\x1a\n\x08ListItem\x12\x0e\n\x02id\x18\x01 \x01(\tR\x02id\"\xbf\x01\n\x0cListResponse\x12#\n\x07vectors\x18\x01 \x03(\x0b\x32\t.ListItemR\x07vectors\x12\x30\n\npagination\x18\x02 \x01(\x0b\x32\x0b.PaginationH\x00R\npagination\x88\x01\x01\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageH\x01R\x05usage\x88\x01\x01\x42\r\n\x0b_paginationB\x08\n\x06_usage\"\xbd\x01\n\x0bQueryVector\x12\x16\n\x06values\x18\x01 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12\x13\n\x05top_k\x18\x02 \x01(\rR\x04topK\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12/\n\x06\x66ilter\x18\x04 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"\xd1\x02\n\x0cQueryRequest\x12\x1c\n\tnamespace\x18\x01 \x01(\tR\tnamespace\x12\x18\n\x05top_k\x18\x02 \x01(\rB\x03\xe0\x41\x02R\x04topK\x12/\n\x06\x66ilter\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\x12%\n\x0einclude_values\x18\x04 \x01(\x08R\rincludeValues\x12)\n\x10include_metadata\x18\x05 \x01(\x08R\x0fincludeMetadata\x12*\n\x07queries\x18\x06 \x03(\x0b\x32\x0c.QueryVectorB\x02\x18\x01R\x07queries\x12\x16\n\x06vector\x18\x07 \x03(\x02R\x06vector\x12\x32\n\rsparse_vector\x18\t \x01(\x0b\x32\r.SparseValuesR\x0csparseVector\x12\x0e\n\x02id\x18\x08 \x01(\tR\x02id\"[\n\x12SingleQueryResults\x12\'\n\x07matches\x18\x01 \x03(\x0b\x32\r.ScoredVectorR\x07matches\x12\x1c\n\tnamespace\x18\x02 \x01(\tR\tnamespace\"\xb6\x01\n\rQueryResponse\x12\x31\n\x07results\x18\x01 \x03(\x0b\x32\x13.SingleQueryResultsB\x02\x18\x01R\x07results\x12\'\n\x07matches\x18\x02 \x03(\x0b\x32\r.ScoredVectorR\x07matches\x12\x1c\n\tnamespace\x18\x03 \x01(\tR\tnamespace\x12!\n\x05usage\x18\x04 \x01(\x0b\x32\x06.UsageH\x00R\x05usage\x88\x01\x01\x42\x08\n\x06_usage\":\n\x05Usage\x12\"\n\nread_units\x18\x01 \x01(\rH\x00R\treadUnits\x88\x01\x01\x42\r\n\x0b_read_units\"\xca\x01\n\rUpdateRequest\x12\x13\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02R\x02id\x12\x16\n\x06values\x18\x02 \x03(\x02R\x06values\x12\x32\n\rsparse_values\x18\x05 \x01(\x0b\x32\r.SparseValuesR\x0csparseValues\x12:\n\x0cset_metadata\x18\x03 \x01(\x0b\x32\x17.google.protobuf.StructR\x0bsetMetadata\x12\x1c\n\tnamespace\x18\x04 \x01(\tR\tnamespace\"\x10\n\x0eUpdateResponse\"L\n\x19\x44\x65scribeIndexStatsRequest\x12/\n\x06\x66ilter\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\x06\x66ilter\"5\n\x10NamespaceSummary\x12!\n\x0cvector_count\x18\x01 \x01(\rR\x0bvectorCount\"\x9f\x03\n\x1a\x44\x65scribeIndexStatsResponse\x12K\n\nnamespaces\x18\x01 \x03(\x0b\x32+.DescribeIndexStatsResponse.NamespacesEntryR\nnamespaces\x12!\n\tdimension\x18\x02 \x01(\rH\x00R\tdimension\x88\x01\x01\x12%\n\x0eindex_fullness\x18\x03 \x01(\x02R\rindexFullness\x12,\n\x12total_vector_count\x18\x04 \x01(\rR\x10totalVectorCount\x12\x1b\n\x06metric\x18\x05 \x01(\tH\x01R\x06metric\x88\x01\x01\x12$\n\x0bvector_type\x18\x06 \x01(\tH\x02R\nvectorType\x88\x01\x01\x1aP\n\x0fNamespacesEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x11.NamespaceSummaryR\x05value:\x02\x38\x01\x42\x0c\n\n_dimensionB\t\n\x07_metricB\x0e\n\x0c_vector_type2\xb9\x04\n\rVectorService\x12\x45\n\x06Upsert\x12\x0e.UpsertRequest\x1a\x0f.UpsertResponse\"\x1a\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/upsert:\x01*\x12X\n\x06\x44\x65lete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"-\x82\xd3\xe4\x93\x02\'\"\x0f/vectors/delete:\x01*Z\x11*\x0f/vectors/delete\x12>\n\x05\x46\x65tch\x12\r.FetchRequest\x1a\x0e.FetchResponse\"\x16\x82\xd3\xe4\x93\x02\x10\x12\x0e/vectors/fetch\x12:\n\x04List\x12\x0c.ListRequest\x1a\r.ListResponse\"\x15\x82\xd3\xe4\x93\x02\x0f\x12\r/vectors/list\x12\x39\n\x05Query\x12\r.QueryRequest\x1a\x0e.QueryResponse\"\x11\x82\xd3\xe4\x93\x02\x0b\"\x06/query:\x01*\x12\x45\n\x06Update\x12\x0e.UpdateRequest\x1a\x0f.UpdateResponse\"\x1a\x82\xd3\xe4\x93\x02\x14\"\x0f/vectors/update:\x01*\x12\x88\x01\n\x12\x44\x65scribeIndexStats\x12\x1a.DescribeIndexStatsRequest\x1a\x1b.DescribeIndexStatsResponse\"9\x82\xd3\xe4\x93\x02\x33\"\x15/describe_index_stats:\x01*Z\x17\x12\x15/describe_index_statsBS\n\x11io.pinecone.protoP\x01Z None: ... - -class Vector(_message.Message): - __slots__ = ("id", "values", "sparse_values", "metadata") - ID_FIELD_NUMBER: _ClassVar[int] - VALUES_FIELD_NUMBER: _ClassVar[int] - SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] - METADATA_FIELD_NUMBER: _ClassVar[int] - id: str - values: _containers.RepeatedScalarFieldContainer[float] - sparse_values: SparseValues - metadata: _struct_pb2.Struct - def __init__(self, id: _Optional[str] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... - -class ScoredVector(_message.Message): - __slots__ = ("id", "score", "values", "sparse_values", "metadata") - ID_FIELD_NUMBER: _ClassVar[int] - SCORE_FIELD_NUMBER: _ClassVar[int] - VALUES_FIELD_NUMBER: _ClassVar[int] - SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] - METADATA_FIELD_NUMBER: _ClassVar[int] - id: str - score: float - values: _containers.RepeatedScalarFieldContainer[float] - sparse_values: SparseValues - metadata: _struct_pb2.Struct - def __init__(self, id: _Optional[str] = ..., score: _Optional[float] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... - -class RequestUnion(_message.Message): - __slots__ = ("upsert", "delete", "update") - UPSERT_FIELD_NUMBER: _ClassVar[int] - DELETE_FIELD_NUMBER: _ClassVar[int] - UPDATE_FIELD_NUMBER: _ClassVar[int] - upsert: UpsertRequest - delete: DeleteRequest - update: UpdateRequest - def __init__(self, upsert: _Optional[_Union[UpsertRequest, _Mapping]] = ..., delete: _Optional[_Union[DeleteRequest, _Mapping]] = ..., update: _Optional[_Union[UpdateRequest, _Mapping]] = ...) -> None: ... - -class UpsertRequest(_message.Message): - __slots__ = ("vectors", "namespace") - VECTORS_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - vectors: _containers.RepeatedCompositeFieldContainer[Vector] - namespace: str - def __init__(self, vectors: _Optional[_Iterable[_Union[Vector, _Mapping]]] = ..., namespace: _Optional[str] = ...) -> None: ... - -class UpsertResponse(_message.Message): - __slots__ = ("upserted_count",) - UPSERTED_COUNT_FIELD_NUMBER: _ClassVar[int] - upserted_count: int - def __init__(self, upserted_count: _Optional[int] = ...) -> None: ... - -class DeleteRequest(_message.Message): - __slots__ = ("ids", "delete_all", "namespace", "filter") - IDS_FIELD_NUMBER: _ClassVar[int] - DELETE_ALL_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - FILTER_FIELD_NUMBER: _ClassVar[int] - ids: _containers.RepeatedScalarFieldContainer[str] - delete_all: bool - namespace: str - filter: _struct_pb2.Struct - def __init__(self, ids: _Optional[_Iterable[str]] = ..., delete_all: bool = ..., namespace: _Optional[str] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... - -class DeleteResponse(_message.Message): - __slots__ = () - def __init__(self) -> None: ... - -class FetchRequest(_message.Message): - __slots__ = ("ids", "namespace") - IDS_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - ids: _containers.RepeatedScalarFieldContainer[str] - namespace: str - def __init__(self, ids: _Optional[_Iterable[str]] = ..., namespace: _Optional[str] = ...) -> None: ... - -class FetchResponse(_message.Message): - __slots__ = ("vectors", "namespace", "usage") - class VectorsEntry(_message.Message): - __slots__ = ("key", "value") - KEY_FIELD_NUMBER: _ClassVar[int] - VALUE_FIELD_NUMBER: _ClassVar[int] - key: str - value: Vector - def __init__(self, key: _Optional[str] = ..., value: _Optional[_Union[Vector, _Mapping]] = ...) -> None: ... - VECTORS_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - USAGE_FIELD_NUMBER: _ClassVar[int] - vectors: _containers.MessageMap[str, Vector] - namespace: str - usage: Usage - def __init__(self, vectors: _Optional[_Mapping[str, Vector]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... - -class ListRequest(_message.Message): - __slots__ = ("prefix", "limit", "pagination_token", "namespace") - PREFIX_FIELD_NUMBER: _ClassVar[int] - LIMIT_FIELD_NUMBER: _ClassVar[int] - PAGINATION_TOKEN_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - prefix: str - limit: int - pagination_token: str - namespace: str - def __init__(self, prefix: _Optional[str] = ..., limit: _Optional[int] = ..., pagination_token: _Optional[str] = ..., namespace: _Optional[str] = ...) -> None: ... - -class Pagination(_message.Message): - __slots__ = ("next",) - NEXT_FIELD_NUMBER: _ClassVar[int] - next: str - def __init__(self, next: _Optional[str] = ...) -> None: ... - -class ListItem(_message.Message): - __slots__ = ("id",) - ID_FIELD_NUMBER: _ClassVar[int] - id: str - def __init__(self, id: _Optional[str] = ...) -> None: ... - -class ListResponse(_message.Message): - __slots__ = ("vectors", "pagination", "namespace", "usage") - VECTORS_FIELD_NUMBER: _ClassVar[int] - PAGINATION_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - USAGE_FIELD_NUMBER: _ClassVar[int] - vectors: _containers.RepeatedCompositeFieldContainer[ListItem] - pagination: Pagination - namespace: str - usage: Usage - def __init__(self, vectors: _Optional[_Iterable[_Union[ListItem, _Mapping]]] = ..., pagination: _Optional[_Union[Pagination, _Mapping]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... - -class QueryVector(_message.Message): - __slots__ = ("values", "sparse_values", "top_k", "namespace", "filter") - VALUES_FIELD_NUMBER: _ClassVar[int] - SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] - TOP_K_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - FILTER_FIELD_NUMBER: _ClassVar[int] - values: _containers.RepeatedScalarFieldContainer[float] - sparse_values: SparseValues - top_k: int - namespace: str - filter: _struct_pb2.Struct - def __init__(self, values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., top_k: _Optional[int] = ..., namespace: _Optional[str] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... - -class QueryRequest(_message.Message): - __slots__ = ("namespace", "top_k", "filter", "include_values", "include_metadata", "queries", "vector", "sparse_vector", "id") - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - TOP_K_FIELD_NUMBER: _ClassVar[int] - FILTER_FIELD_NUMBER: _ClassVar[int] - INCLUDE_VALUES_FIELD_NUMBER: _ClassVar[int] - INCLUDE_METADATA_FIELD_NUMBER: _ClassVar[int] - QUERIES_FIELD_NUMBER: _ClassVar[int] - VECTOR_FIELD_NUMBER: _ClassVar[int] - SPARSE_VECTOR_FIELD_NUMBER: _ClassVar[int] - ID_FIELD_NUMBER: _ClassVar[int] - namespace: str - top_k: int - filter: _struct_pb2.Struct - include_values: bool - include_metadata: bool - queries: _containers.RepeatedCompositeFieldContainer[QueryVector] - vector: _containers.RepeatedScalarFieldContainer[float] - sparse_vector: SparseValues - id: str - def __init__(self, namespace: _Optional[str] = ..., top_k: _Optional[int] = ..., filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., include_values: bool = ..., include_metadata: bool = ..., queries: _Optional[_Iterable[_Union[QueryVector, _Mapping]]] = ..., vector: _Optional[_Iterable[float]] = ..., sparse_vector: _Optional[_Union[SparseValues, _Mapping]] = ..., id: _Optional[str] = ...) -> None: ... - -class SingleQueryResults(_message.Message): - __slots__ = ("matches", "namespace") - MATCHES_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - matches: _containers.RepeatedCompositeFieldContainer[ScoredVector] - namespace: str - def __init__(self, matches: _Optional[_Iterable[_Union[ScoredVector, _Mapping]]] = ..., namespace: _Optional[str] = ...) -> None: ... - -class QueryResponse(_message.Message): - __slots__ = ("results", "matches", "namespace", "usage") - RESULTS_FIELD_NUMBER: _ClassVar[int] - MATCHES_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - USAGE_FIELD_NUMBER: _ClassVar[int] - results: _containers.RepeatedCompositeFieldContainer[SingleQueryResults] - matches: _containers.RepeatedCompositeFieldContainer[ScoredVector] - namespace: str - usage: Usage - def __init__(self, results: _Optional[_Iterable[_Union[SingleQueryResults, _Mapping]]] = ..., matches: _Optional[_Iterable[_Union[ScoredVector, _Mapping]]] = ..., namespace: _Optional[str] = ..., usage: _Optional[_Union[Usage, _Mapping]] = ...) -> None: ... - -class Usage(_message.Message): - __slots__ = ("read_units",) - READ_UNITS_FIELD_NUMBER: _ClassVar[int] - read_units: int - def __init__(self, read_units: _Optional[int] = ...) -> None: ... - -class UpdateRequest(_message.Message): - __slots__ = ("id", "values", "sparse_values", "set_metadata", "namespace") - ID_FIELD_NUMBER: _ClassVar[int] - VALUES_FIELD_NUMBER: _ClassVar[int] - SPARSE_VALUES_FIELD_NUMBER: _ClassVar[int] - SET_METADATA_FIELD_NUMBER: _ClassVar[int] - NAMESPACE_FIELD_NUMBER: _ClassVar[int] - id: str - values: _containers.RepeatedScalarFieldContainer[float] - sparse_values: SparseValues - set_metadata: _struct_pb2.Struct - namespace: str - def __init__(self, id: _Optional[str] = ..., values: _Optional[_Iterable[float]] = ..., sparse_values: _Optional[_Union[SparseValues, _Mapping]] = ..., set_metadata: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., namespace: _Optional[str] = ...) -> None: ... - -class UpdateResponse(_message.Message): - __slots__ = () - def __init__(self) -> None: ... - -class DescribeIndexStatsRequest(_message.Message): - __slots__ = ("filter",) - FILTER_FIELD_NUMBER: _ClassVar[int] - filter: _struct_pb2.Struct - def __init__(self, filter: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...) -> None: ... - -class NamespaceSummary(_message.Message): - __slots__ = ("vector_count",) - VECTOR_COUNT_FIELD_NUMBER: _ClassVar[int] - vector_count: int - def __init__(self, vector_count: _Optional[int] = ...) -> None: ... - -class DescribeIndexStatsResponse(_message.Message): - __slots__ = ("namespaces", "dimension", "index_fullness", "total_vector_count", "metric", "vector_type") - class NamespacesEntry(_message.Message): - __slots__ = ("key", "value") - KEY_FIELD_NUMBER: _ClassVar[int] - VALUE_FIELD_NUMBER: _ClassVar[int] - key: str - value: NamespaceSummary - def __init__(self, key: _Optional[str] = ..., value: _Optional[_Union[NamespaceSummary, _Mapping]] = ...) -> None: ... - NAMESPACES_FIELD_NUMBER: _ClassVar[int] - DIMENSION_FIELD_NUMBER: _ClassVar[int] - INDEX_FULLNESS_FIELD_NUMBER: _ClassVar[int] - TOTAL_VECTOR_COUNT_FIELD_NUMBER: _ClassVar[int] - METRIC_FIELD_NUMBER: _ClassVar[int] - VECTOR_TYPE_FIELD_NUMBER: _ClassVar[int] - namespaces: _containers.MessageMap[str, NamespaceSummary] - dimension: int - index_fullness: float - total_vector_count: int - metric: str - vector_type: str - def __init__(self, namespaces: _Optional[_Mapping[str, NamespaceSummary]] = ..., dimension: _Optional[int] = ..., index_fullness: _Optional[float] = ..., total_vector_count: _Optional[int] = ..., metric: _Optional[str] = ..., vector_type: _Optional[str] = ...) -> None: ... diff --git a/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py b/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py deleted file mode 100644 index 4c80e120f..000000000 --- a/pinecone/core/grpc/protos/db_data_2025_01_pb2_grpc.py +++ /dev/null @@ -1,309 +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.db_data_2025_01_pb2 as db__data__2025__01__pb2 - - -class VectorServiceStub(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - def __init__(self, channel) -> None: - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.Upsert = channel.unary_unary( - '/VectorService/Upsert', - request_serializer=db__data__2025__01__pb2.UpsertRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.UpsertResponse.FromString, - ) - self.Delete = channel.unary_unary( - '/VectorService/Delete', - request_serializer=db__data__2025__01__pb2.DeleteRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.DeleteResponse.FromString, - ) - self.Fetch = channel.unary_unary( - '/VectorService/Fetch', - request_serializer=db__data__2025__01__pb2.FetchRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.FetchResponse.FromString, - ) - self.List = channel.unary_unary( - '/VectorService/List', - request_serializer=db__data__2025__01__pb2.ListRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.ListResponse.FromString, - ) - self.Query = channel.unary_unary( - '/VectorService/Query', - request_serializer=db__data__2025__01__pb2.QueryRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.QueryResponse.FromString, - ) - self.Update = channel.unary_unary( - '/VectorService/Update', - request_serializer=db__data__2025__01__pb2.UpdateRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.UpdateResponse.FromString, - ) - self.DescribeIndexStats = channel.unary_unary( - '/VectorService/DescribeIndexStats', - request_serializer=db__data__2025__01__pb2.DescribeIndexStatsRequest.SerializeToString, - response_deserializer=db__data__2025__01__pb2.DescribeIndexStatsResponse.FromString, - ) - - -class VectorServiceServicer(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - def Upsert(self, request, context): - """Upsert vectors - - Writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. - - For guidance and examples, see [Upsert data](https://docs.pinecone.io/guides/data/upsert-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def Delete(self, request, context): - """Delete vectors - - Delete vectors by id from a single namespace. - - For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def Fetch(self, request, context): - """Fetch vectors - - Look up and returns vectors by ID from a single namespace. The returned vectors include the vector data and/or metadata. - - For guidance and examples, see [Fetch data](https://docs.pinecone.io/guides/data/fetch-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def List(self, request, context): - """List vector IDs - - List the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. - - This returns up to 100 IDs at a time by default in sorted order (bitwise/"C" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. - - For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). - - **Note:** This is supported only for serverless indexes. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def Query(self, request, context): - """Query vectors - - Searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. - - For guidance and examples, see [Query data](https://docs.pinecone.io/guides/data/query-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def Update(self, request, context): - """Update a vector - - Update a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. - - For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def DescribeIndexStats(self, request, context): - """Get index stats - - Return statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. - - Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - -def add_VectorServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - 'Upsert': grpc.unary_unary_rpc_method_handler( - servicer.Upsert, - request_deserializer=db__data__2025__01__pb2.UpsertRequest.FromString, - response_serializer=db__data__2025__01__pb2.UpsertResponse.SerializeToString, - ), - 'Delete': grpc.unary_unary_rpc_method_handler( - servicer.Delete, - request_deserializer=db__data__2025__01__pb2.DeleteRequest.FromString, - response_serializer=db__data__2025__01__pb2.DeleteResponse.SerializeToString, - ), - 'Fetch': grpc.unary_unary_rpc_method_handler( - servicer.Fetch, - request_deserializer=db__data__2025__01__pb2.FetchRequest.FromString, - response_serializer=db__data__2025__01__pb2.FetchResponse.SerializeToString, - ), - 'List': grpc.unary_unary_rpc_method_handler( - servicer.List, - request_deserializer=db__data__2025__01__pb2.ListRequest.FromString, - response_serializer=db__data__2025__01__pb2.ListResponse.SerializeToString, - ), - 'Query': grpc.unary_unary_rpc_method_handler( - servicer.Query, - request_deserializer=db__data__2025__01__pb2.QueryRequest.FromString, - response_serializer=db__data__2025__01__pb2.QueryResponse.SerializeToString, - ), - 'Update': grpc.unary_unary_rpc_method_handler( - servicer.Update, - request_deserializer=db__data__2025__01__pb2.UpdateRequest.FromString, - response_serializer=db__data__2025__01__pb2.UpdateResponse.SerializeToString, - ), - 'DescribeIndexStats': grpc.unary_unary_rpc_method_handler( - servicer.DescribeIndexStats, - request_deserializer=db__data__2025__01__pb2.DescribeIndexStatsRequest.FromString, - response_serializer=db__data__2025__01__pb2.DescribeIndexStatsResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'VectorService', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - - - # This class is part of an EXPERIMENTAL API. -class VectorService(object): - """The `VectorService` interface is exposed by Pinecone's vector index services. - This service could also be called a `gRPC` service or a `REST`-like api. - """ - - @staticmethod - def Upsert(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/Upsert', - db__data__2025__01__pb2.UpsertRequest.SerializeToString, - db__data__2025__01__pb2.UpsertResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def Delete(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/Delete', - db__data__2025__01__pb2.DeleteRequest.SerializeToString, - db__data__2025__01__pb2.DeleteResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def Fetch(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/Fetch', - db__data__2025__01__pb2.FetchRequest.SerializeToString, - db__data__2025__01__pb2.FetchResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def List(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/List', - db__data__2025__01__pb2.ListRequest.SerializeToString, - db__data__2025__01__pb2.ListResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def Query(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/Query', - db__data__2025__01__pb2.QueryRequest.SerializeToString, - db__data__2025__01__pb2.QueryResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def Update(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/Update', - db__data__2025__01__pb2.UpdateRequest.SerializeToString, - db__data__2025__01__pb2.UpdateResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) - - @staticmethod - def DescribeIndexStats(request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None): - return grpc.experimental.unary_unary(request, target, '/VectorService/DescribeIndexStats', - db__data__2025__01__pb2.DescribeIndexStatsRequest.SerializeToString, - db__data__2025__01__pb2.DescribeIndexStatsResponse.FromString, - options, channel_credentials, - insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/pinecone/core/openapi/db_control/__init__.py b/pinecone/core/openapi/db_control/__init__.py deleted file mode 100644 index e8106fac9..000000000 --- a/pinecone/core/openapi/db_control/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# flake8: noqa - -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.openapi_support.api_client import ApiClient - -# import Configuration -from pinecone.openapi_support.configuration import Configuration - -# import exceptions -from pinecone.openapi_support.exceptions import PineconeException -from pinecone.openapi_support.exceptions import PineconeApiAttributeError -from pinecone.openapi_support.exceptions import PineconeApiTypeError -from pinecone.openapi_support.exceptions import PineconeApiValueError -from pinecone.openapi_support.exceptions import PineconeApiKeyError -from pinecone.openapi_support.exceptions import PineconeApiException - -API_VERSION = "2025-01" diff --git a/pinecone/core/openapi/db_control/api/__init__.py b/pinecone/core/openapi/db_control/api/__init__.py deleted file mode 100644 index 820d21905..000000000 --- a/pinecone/core/openapi/db_control/api/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# 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.openapi.db_control.apis import ManageIndexesApi diff --git a/pinecone/core/openapi/db_control/api/manage_indexes_api.py b/pinecone/core/openapi/db_control/api/manage_indexes_api.py deleted file mode 100644 index 2d2f464d0..000000000 --- a/pinecone/core/openapi/db_control/api/manage_indexes_api.py +++ /dev/null @@ -1,1350 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support import ApiClient, AsyncioApiClient -from pinecone.openapi_support.endpoint_utils import ( - ExtraOpenApiKwargsTypedDict, - KwargsWithOpenApiKwargDefaultsTypedDict, -) -from pinecone.openapi_support.endpoint import Endpoint as _Endpoint, ExtraOpenApiKwargsTypedDict -from pinecone.openapi_support.asyncio_endpoint import AsyncioEndpoint as _AsyncioEndpoint -from pinecone.openapi_support.model_utils import ( # noqa: F401 - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.openapi.db_control.model.collection_list import CollectionList -from pinecone.core.openapi.db_control.model.collection_model import CollectionModel -from pinecone.core.openapi.db_control.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.openapi.db_control.model.create_collection_request import CreateCollectionRequest -from pinecone.core.openapi.db_control.model.create_index_for_model_request import ( - CreateIndexForModelRequest, -) -from pinecone.core.openapi.db_control.model.create_index_request import CreateIndexRequest -from pinecone.core.openapi.db_control.model.error_response import ErrorResponse -from pinecone.core.openapi.db_control.model.index_list import IndexList -from pinecone.core.openapi.db_control.model.index_model import IndexModel - - -class ManageIndexesApi: - """NOTE: This class is @generated using OpenAPI. - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def __configure_index( - self, index_name, configure_index_request, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Configure an index # noqa: E501 - - This operation configures an existing index. For serverless indexes, you can configure index deletion protection, tags, and integrated inference embedding settings for the index. For pod-based indexes, you can configure the pod size, number of replicas, tags, and index deletion protection. It is not possible to change the pod type of a pod-based index. However, you can create a collection from a pod-based index and then [create a new pod-based index with a different pod type](http://docs.pinecone.io/guides/indexes/pods/create-a-pod-based-index#create-a-pod-index-from-a-collection) from the collection. For guidance and examples, see [Configure an index](http://docs.pinecone.io/guides/indexes/pods/manage-pod-based-indexes). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.configure_index(index_name, configure_index_request, async_req=True) - >>> result = thread.get() - - Args: - index_name (str): The name of the index to configure. - configure_index_request (ConfigureIndexRequest): The desired pod size and replica configuration for the index. - - Keyword Args: - _return_http_data_only (bool): response data without head status - 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. - async_req (bool): execute request asynchronously - - Returns: - IndexModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - 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": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/{index_name}", - "operation_id": "configure_index", - "http_method": "PATCH", - "servers": None, - }, - params_map={ - "all": ["index_name", "configure_index_request"], - "required": ["index_name", "configure_index_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "index_name": (str,), - "configure_index_request": (ConfigureIndexRequest,), - }, - "attribute_map": {"index_name": "index_name"}, - "location_map": {"index_name": "path", "configure_index_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__configure_index, - ) - - def __create_collection( - self, create_collection_request, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Create a collection # noqa: E501 - - This operation creates a Pinecone collection. Serverless indexes do not support 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.create_collection(create_collection_request, async_req=True) - >>> result = thread.get() - - Args: - create_collection_request (CreateCollectionRequest): The desired configuration for 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. - async_req (bool): execute request asynchronously - - Returns: - CollectionModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["create_collection_request"] = create_collection_request - return self.call_with_http_info(**kwargs) - - self.create_collection = _Endpoint( - settings={ - "response_type": (CollectionModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "create_collection", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["create_collection_request"], - "required": ["create_collection_request"], - "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": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_collection, - ) - - def __create_index(self, create_index_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Create an 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. For guidance and examples, see [Create an index](https://docs.pinecone.io/guides/indexes/create-an-index#create-a-serverless-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_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. - async_req (bool): execute request asynchronously - - Returns: - IndexModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - 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": None, - }, - 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 __create_index_for_model( - self, create_index_for_model_request, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Create an index for an embedding model # noqa: E501 - - This operation creates a serverless integrated inference index for a specific embedding model. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) for available models and model details. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.create_index_for_model(create_index_for_model_request, async_req=True) - >>> result = thread.get() - - Args: - create_index_for_model_request (CreateIndexForModelRequest): The desired configuration for the index and associated embedding model. - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - async_req (bool): execute request asynchronously - - Returns: - IndexModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["create_index_for_model_request"] = create_index_for_model_request - return self.call_with_http_info(**kwargs) - - self.create_index_for_model = _Endpoint( - settings={ - "response_type": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/create-for-model", - "operation_id": "create_index_for_model", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["create_index_for_model_request"], - "required": ["create_index_for_model_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"create_index_for_model_request": (CreateIndexForModelRequest,)}, - "attribute_map": {}, - "location_map": {"create_index_for_model_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_index_for_model, - ) - - def __delete_collection(self, collection_name, **kwargs: ExtraOpenApiKwargsTypedDict): - """Delete a collection # noqa: E501 - - This operation deletes an existing collection. Serverless indexes do not support 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.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. - async_req (bool): execute request asynchronously - - Returns: - None - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["collection_name"] = collection_name - return self.call_with_http_info(**kwargs) - - self.delete_collection = _Endpoint( - settings={ - "response_type": None, - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collection_name}", - "operation_id": "delete_collection", - "http_method": "DELETE", - "servers": None, - }, - 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": "collection_name"}, - "location_map": {"collection_name": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__delete_collection, - ) - - def __delete_index(self, index_name, **kwargs: ExtraOpenApiKwargsTypedDict): - """Delete an 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. - async_req (bool): execute request asynchronously - - Returns: - None - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - 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": None, - }, - 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_collection(self, collection_name, **kwargs: ExtraOpenApiKwargsTypedDict): - """Describe a collection # noqa: E501 - - This operation gets a description of a collection. Serverless indexes do not support 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.describe_collection(collection_name, async_req=True) - >>> result = thread.get() - - Args: - collection_name (str): The name of the collection 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. - async_req (bool): execute request asynchronously - - Returns: - CollectionModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["collection_name"] = collection_name - return self.call_with_http_info(**kwargs) - - self.describe_collection = _Endpoint( - settings={ - "response_type": (CollectionModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collection_name}", - "operation_id": "describe_collection", - "http_method": "GET", - "servers": None, - }, - 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": "collection_name"}, - "location_map": {"collection_name": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__describe_collection, - ) - - def __describe_index(self, index_name, **kwargs: ExtraOpenApiKwargsTypedDict): - """Describe an 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. - async_req (bool): execute request asynchronously - - Returns: - IndexModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - 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": None, - }, - 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_collections(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """List collections # noqa: E501 - - This operation returns a list of all collections in a project. Serverless indexes do not support 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. - async_req (bool): execute request asynchronously - - Returns: - CollectionList - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - return self.call_with_http_info(**kwargs) - - self.list_collections = _Endpoint( - settings={ - "response_type": (CollectionList,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "list_collections", - "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=__list_collections, - ) - - def __list_indexes(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """List indexes # noqa: E501 - - This operation returns a list of all indexes in a 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. - async_req (bool): execute request asynchronously - - Returns: - IndexList - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - 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": 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=__list_indexes, - ) - - -class AsyncioManageIndexesApi: - """NOTE: This class is @generated using OpenAPI - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = AsyncioApiClient() - self.api_client = api_client - - async def __configure_index(self, index_name, configure_index_request, **kwargs): - """Configure an index # noqa: E501 - - This operation configures an existing index. For serverless indexes, you can configure index deletion protection, tags, and integrated inference embedding settings for the index. For pod-based indexes, you can configure the pod size, number of replicas, tags, and index deletion protection. It is not possible to change the pod type of a pod-based index. However, you can create a collection from a pod-based index and then [create a new pod-based index with a different pod type](http://docs.pinecone.io/guides/indexes/pods/create-a-pod-based-index#create-a-pod-index-from-a-collection) from the collection. For guidance and examples, see [Configure an index](http://docs.pinecone.io/guides/indexes/pods/manage-pod-based-indexes). # noqa: E501 - - - Args: - index_name (str): The name of the index to configure. - configure_index_request (ConfigureIndexRequest): The desired pod size and replica configuration for the index. - - Keyword Args: - _return_http_data_only (bool): response data without head status - 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. - - Returns: - IndexModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["index_name"] = index_name - kwargs["configure_index_request"] = configure_index_request - return await self.call_with_http_info(**kwargs) - - self.configure_index = _AsyncioEndpoint( - settings={ - "response_type": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/{index_name}", - "operation_id": "configure_index", - "http_method": "PATCH", - "servers": None, - }, - params_map={ - "all": ["index_name", "configure_index_request"], - "required": ["index_name", "configure_index_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "index_name": (str,), - "configure_index_request": (ConfigureIndexRequest,), - }, - "attribute_map": {"index_name": "index_name"}, - "location_map": {"index_name": "path", "configure_index_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__configure_index, - ) - - async def __create_collection(self, create_collection_request, **kwargs): - """Create a collection # noqa: E501 - - This operation creates a Pinecone collection. Serverless indexes do not support collections. # noqa: E501 - - - Args: - create_collection_request (CreateCollectionRequest): The desired configuration for 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. - - Returns: - CollectionModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["create_collection_request"] = create_collection_request - return await self.call_with_http_info(**kwargs) - - self.create_collection = _AsyncioEndpoint( - settings={ - "response_type": (CollectionModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "create_collection", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["create_collection_request"], - "required": ["create_collection_request"], - "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": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_collection, - ) - - async def __create_index(self, create_index_request, **kwargs): - """Create an 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. For guidance and examples, see [Create an index](https://docs.pinecone.io/guides/indexes/create-an-index#create-a-serverless-index). # noqa: E501 - - - 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. - - Returns: - IndexModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["create_index_request"] = create_index_request - return await self.call_with_http_info(**kwargs) - - self.create_index = _AsyncioEndpoint( - settings={ - "response_type": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes", - "operation_id": "create_index", - "http_method": "POST", - "servers": None, - }, - 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, - ) - - async def __create_index_for_model(self, create_index_for_model_request, **kwargs): - """Create an index for an embedding model # noqa: E501 - - This operation creates a serverless integrated inference index for a specific embedding model. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) for available models and model details. # noqa: E501 - - - Args: - create_index_for_model_request (CreateIndexForModelRequest): The desired configuration for the index and associated embedding model. - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - - Returns: - IndexModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["create_index_for_model_request"] = create_index_for_model_request - return await self.call_with_http_info(**kwargs) - - self.create_index_for_model = _AsyncioEndpoint( - settings={ - "response_type": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/create-for-model", - "operation_id": "create_index_for_model", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["create_index_for_model_request"], - "required": ["create_index_for_model_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"create_index_for_model_request": (CreateIndexForModelRequest,)}, - "attribute_map": {}, - "location_map": {"create_index_for_model_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__create_index_for_model, - ) - - async def __delete_collection(self, collection_name, **kwargs): - """Delete a collection # noqa: E501 - - This operation deletes an existing collection. Serverless indexes do not support collections. # noqa: E501 - - - 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. - - Returns: - None - """ - self._process_openapi_kwargs(kwargs) - kwargs["collection_name"] = collection_name - return await self.call_with_http_info(**kwargs) - - self.delete_collection = _AsyncioEndpoint( - settings={ - "response_type": None, - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collection_name}", - "operation_id": "delete_collection", - "http_method": "DELETE", - "servers": None, - }, - 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": "collection_name"}, - "location_map": {"collection_name": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__delete_collection, - ) - - async def __delete_index(self, index_name, **kwargs): - """Delete an index # noqa: E501 - - This operation deletes an existing index. # noqa: E501 - - - 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. - - Returns: - None - """ - self._process_openapi_kwargs(kwargs) - kwargs["index_name"] = index_name - return await self.call_with_http_info(**kwargs) - - self.delete_index = _AsyncioEndpoint( - settings={ - "response_type": None, - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/{index_name}", - "operation_id": "delete_index", - "http_method": "DELETE", - "servers": None, - }, - 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, - ) - - async def __describe_collection(self, collection_name, **kwargs): - """Describe a collection # noqa: E501 - - This operation gets a description of a collection. Serverless indexes do not support collections. # noqa: E501 - - - Args: - collection_name (str): The name of the collection 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. - - Returns: - CollectionModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["collection_name"] = collection_name - return await self.call_with_http_info(**kwargs) - - self.describe_collection = _AsyncioEndpoint( - settings={ - "response_type": (CollectionModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections/{collection_name}", - "operation_id": "describe_collection", - "http_method": "GET", - "servers": None, - }, - 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": "collection_name"}, - "location_map": {"collection_name": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__describe_collection, - ) - - async def __describe_index(self, index_name, **kwargs): - """Describe an index # noqa: E501 - - Get a description of an index. # noqa: E501 - - - 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. - - Returns: - IndexModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["index_name"] = index_name - return await self.call_with_http_info(**kwargs) - - self.describe_index = _AsyncioEndpoint( - settings={ - "response_type": (IndexModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes/{index_name}", - "operation_id": "describe_index", - "http_method": "GET", - "servers": None, - }, - 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, - ) - - async def __list_collections(self, **kwargs): - """List collections # noqa: E501 - - This operation returns a list of all collections in a project. Serverless indexes do not support collections. # noqa: E501 - - - - 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. - - Returns: - CollectionList - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.list_collections = _AsyncioEndpoint( - settings={ - "response_type": (CollectionList,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/collections", - "operation_id": "list_collections", - "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=__list_collections, - ) - - async def __list_indexes(self, **kwargs): - """List indexes # noqa: E501 - - This operation returns a list of all indexes in a project. # noqa: E501 - - - - 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. - - Returns: - IndexList - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.list_indexes = _AsyncioEndpoint( - settings={ - "response_type": (IndexList,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/indexes", - "operation_id": "list_indexes", - "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=__list_indexes, - ) diff --git a/pinecone/core/openapi/db_control/apis/__init__.py b/pinecone/core/openapi/db_control/apis/__init__.py deleted file mode 100644 index c82584141..000000000 --- a/pinecone/core/openapi/db_control/apis/__init__.py +++ /dev/null @@ -1,16 +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.manage_indexes_api import ManageIndexesApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from pinecone.core.openapi.db_control.api.manage_indexes_api import ManageIndexesApi diff --git a/pinecone/core/openapi/db_control/model/__init__.py b/pinecone/core/openapi/db_control/model/__init__.py deleted file mode 100644 index cfe32b784..000000000 --- a/pinecone/core/openapi/db_control/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/openapi/db_control/model/collection_list.py b/pinecone/core/openapi/db_control/model/collection_list.py deleted file mode 100644 index e36d3d9d1..000000000 --- a/pinecone/core/openapi/db_control/model/collection_list.py +++ /dev/null @@ -1,268 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.collection_model import CollectionModel - - globals()["CollectionModel"] = CollectionModel - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CollectionList") - - -class CollectionList(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "collections": ([CollectionModel],) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "collections": "collections" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """CollectionList - 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,) - collections ([CollectionModel]): [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) -> None: # noqa: E501 - """CollectionList - 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,) - collections ([CollectionModel]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/collection_model.py b/pinecone/core/openapi/db_control/model/collection_model.py deleted file mode 100644 index 88d2334d2..000000000 --- a/pinecone/core/openapi/db_control/model/collection_model.py +++ /dev/null @@ -1,298 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CollectionModel") - - -class CollectionModel(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("status",): { - "INITIALIZING": "Initializing", - "READY": "Ready", - "TERMINATING": "Terminating", - } - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("dimension",): {"inclusive_maximum": 20000, "inclusive_minimum": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "status": (str,), # noqa: E501 - "environment": (str,), # noqa: E501 - "size": (int,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "vector_count": (int,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "name": "name", # noqa: E501 - "status": "status", # noqa: E501 - "environment": "environment", # noqa: E501 - "size": "size", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "vector_count": "vector_count", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], name, status, environment, *args, **kwargs) -> T: # noqa: E501 - """CollectionModel - a model defined in OpenAPI - - Args: - name (str): The name of the collection. - status (str): The status of the collection. - environment (str): The environment where the collection 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,) - size (int): The size of the collection in bytes. [optional] # noqa: E501 - dimension (int): The dimension of the vectors stored in each record held in the collection. [optional] # noqa: E501 - vector_count (int): The number of records stored in 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.status = status - 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, name, status, environment, *args, **kwargs) -> None: # noqa: E501 - """CollectionModel - a model defined in OpenAPI - - Args: - name (str): The name of the collection. - status (str): The status of the collection. - environment (str): The environment where the collection 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,) - size (int): The size of the collection in bytes. [optional] # noqa: E501 - dimension (int): The dimension of the vectors stored in each record held in the collection. [optional] # noqa: E501 - vector_count (int): The number of records stored in 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.status = status - 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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request.py b/pinecone/core/openapi/db_control/model/configure_index_request.py deleted file mode 100644 index 7f4a5cf35..000000000 --- a/pinecone/core/openapi/db_control/model/configure_index_request.py +++ /dev/null @@ -1,290 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.configure_index_request_embed import ( - ConfigureIndexRequestEmbed, - ) - from pinecone.core.openapi.db_control.model.configure_index_request_spec import ( - ConfigureIndexRequestSpec, - ) - from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection - from pinecone.core.openapi.db_control.model.index_tags import IndexTags - - globals()["ConfigureIndexRequestEmbed"] = ConfigureIndexRequestEmbed - globals()["ConfigureIndexRequestSpec"] = ConfigureIndexRequestSpec - globals()["DeletionProtection"] = DeletionProtection - globals()["IndexTags"] = IndexTags - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ConfigureIndexRequest") - - -class ConfigureIndexRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "deletion_protection": (DeletionProtection,), # noqa: E501 - "tags": (IndexTags,), # noqa: E501 - "embed": (ConfigureIndexRequestEmbed,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "spec": "spec", # noqa: E501 - "deletion_protection": "deletion_protection", # noqa: E501 - "tags": "tags", # noqa: E501 - "embed": "embed", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ConfigureIndexRequest - 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,) - spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - embed (ConfigureIndexRequestEmbed): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _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) -> None: # noqa: E501 - """ConfigureIndexRequest - 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,) - spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - embed (ConfigureIndexRequestEmbed): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_embed.py b/pinecone/core/openapi/db_control/model/configure_index_request_embed.py deleted file mode 100644 index 55f12ebfa..000000000 --- a/pinecone/core/openapi/db_control/model/configure_index_request_embed.py +++ /dev/null @@ -1,272 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ConfigureIndexRequestEmbed") - - -class ConfigureIndexRequestEmbed(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "model": (str,), # noqa: E501 - "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "field_map": "field_map", # noqa: E501 - "read_parameters": "read_parameters", # noqa: E501 - "write_parameters": "write_parameters", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ConfigureIndexRequestEmbed - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - model (str): The name of the embedding model to use with the index. The index dimension and model dimension must match, and the index similarity metric must be supported by the model. The index embedding model cannot be changed once set. [optional] # noqa: E501 - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs) -> None: # noqa: E501 - """ConfigureIndexRequestEmbed - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - model (str): The name of the embedding model to use with the index. The index dimension and model dimension must match, and the index similarity metric must be supported by the model. The index embedding model cannot be changed once set. [optional] # noqa: E501 - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_spec.py b/pinecone/core/openapi/db_control/model/configure_index_request_spec.py deleted file mode 100644 index 484ad71dc..000000000 --- a/pinecone/core/openapi/db_control/model/configure_index_request_spec.py +++ /dev/null @@ -1,276 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.configure_index_request_spec_pod import ( - ConfigureIndexRequestSpecPod, - ) - - globals()["ConfigureIndexRequestSpecPod"] = ConfigureIndexRequestSpecPod - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ConfigureIndexRequestSpec") - - -class ConfigureIndexRequestSpec(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "pod": "pod" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], pod, *args, **kwargs) -> T: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py b/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py deleted file mode 100644 index 3a3ea96e0..000000000 --- a/pinecone/core/openapi/db_control/model/configure_index_request_spec_pod.py +++ /dev/null @@ -1,266 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ConfigureIndexRequestSpecPod") - - -class ConfigureIndexRequestSpecPod(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("replicas",): {"inclusive_minimum": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "replicas": "replicas", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ConfigureIndexRequestSpecPod - 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 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) - _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) -> None: # noqa: E501 - """ConfigureIndexRequestSpecPod - 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 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) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/create_collection_request.py b/pinecone/core/openapi/db_control/model/create_collection_request.py deleted file mode 100644 index 0e14dc226..000000000 --- a/pinecone/core/openapi/db_control/model/create_collection_request.py +++ /dev/null @@ -1,274 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CreateCollectionRequest") - - -class CreateCollectionRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("name",): {"max_length": 45, "min_length": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "name": "name", # noqa: E501 - "source": "source", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], name, source, *args, **kwargs) -> T: # noqa: E501 - """CreateCollectionRequest - a model defined in OpenAPI - - Args: - name (str): The name of the collection to be created. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - 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 - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # noqa: E501 - """CreateCollectionRequest - a model defined in OpenAPI - - Args: - name (str): The name of the collection to be created. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - 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 - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/create_index_for_model_request.py b/pinecone/core/openapi/db_control/model/create_index_for_model_request.py deleted file mode 100644 index c7d889a2c..000000000 --- a/pinecone/core/openapi/db_control/model/create_index_for_model_request.py +++ /dev/null @@ -1,310 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.create_index_for_model_request_embed import ( - CreateIndexForModelRequestEmbed, - ) - from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection - from pinecone.core.openapi.db_control.model.index_tags import IndexTags - - globals()["CreateIndexForModelRequestEmbed"] = CreateIndexForModelRequestEmbed - globals()["DeletionProtection"] = DeletionProtection - globals()["IndexTags"] = IndexTags - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CreateIndexForModelRequest") - - -class CreateIndexForModelRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("cloud",): {"GCP": "gcp", "AWS": "aws", "AZURE": "azure"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("name",): {"max_length": 45, "min_length": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "name": (str,), # noqa: E501 - "cloud": (str,), # noqa: E501 - "region": (str,), # noqa: E501 - "embed": (CreateIndexForModelRequestEmbed,), # noqa: E501 - "deletion_protection": (DeletionProtection,), # noqa: E501 - "tags": (IndexTags,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "name": "name", # noqa: E501 - "cloud": "cloud", # noqa: E501 - "region": "region", # noqa: E501 - "embed": "embed", # noqa: E501 - "deletion_protection": "deletion_protection", # noqa: E501 - "tags": "tags", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], name, cloud, region, embed, *args, **kwargs) -> T: # noqa: E501 - """CreateIndexForModelRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - cloud (str): The public cloud where you would like your index hosted. - region (str): The region where you would like your index to be created. - embed (CreateIndexForModelRequestEmbed): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.cloud = cloud - self.region = region - self.embed = embed - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, name, cloud, region, embed, *args, **kwargs) -> None: # noqa: E501 - """CreateIndexForModelRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - cloud (str): The public cloud where you would like your index hosted. - region (str): The region where you would like your index to be created. - embed (CreateIndexForModelRequestEmbed): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.cloud = cloud - self.region = region - self.embed = embed - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py b/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py deleted file mode 100644 index 88de090a4..000000000 --- a/pinecone/core/openapi/db_control/model/create_index_for_model_request_embed.py +++ /dev/null @@ -1,286 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CreateIndexForModelRequestEmbed") - - -class CreateIndexForModelRequestEmbed(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "model": (str,), # noqa: E501 - "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "metric": (str,), # noqa: E501 - "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "field_map": "field_map", # noqa: E501 - "metric": "metric", # noqa: E501 - "read_parameters": "read_parameters", # noqa: E501 - "write_parameters": "write_parameters", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, field_map, *args, **kwargs) -> T: # noqa: E501 - """CreateIndexForModelRequestEmbed - a model defined in OpenAPI - - Args: - model (str): The name of the embedding model to use for the index. - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.field_map = field_map - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, field_map, *args, **kwargs) -> None: # noqa: E501 - """CreateIndexForModelRequestEmbed - a model defined in OpenAPI - - Args: - model (str): The name of the embedding model to use for the index. - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that will be embedded. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.field_map = field_map - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/create_index_request.py b/pinecone/core/openapi/db_control/model/create_index_request.py deleted file mode 100644 index ae61e95a4..000000000 --- a/pinecone/core/openapi/db_control/model/create_index_request.py +++ /dev/null @@ -1,309 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection - from pinecone.core.openapi.db_control.model.index_spec import IndexSpec - from pinecone.core.openapi.db_control.model.index_tags import IndexTags - - globals()["DeletionProtection"] = DeletionProtection - globals()["IndexSpec"] = IndexSpec - globals()["IndexTags"] = IndexTags - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="CreateIndexRequest") - - -class CreateIndexRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("name",): {"max_length": 45, "min_length": 1}, - ("dimension",): {"inclusive_maximum": 20000, "inclusive_minimum": 1}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "spec": (IndexSpec,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "metric": (str,), # noqa: E501 - "deletion_protection": (DeletionProtection,), # noqa: E501 - "tags": (IndexTags,), # noqa: E501 - "vector_type": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "name": "name", # noqa: E501 - "spec": "spec", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "metric": "metric", # noqa: E501 - "deletion_protection": "deletion_protection", # noqa: E501 - "tags": "tags", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], name, spec, *args, **kwargs) -> T: # noqa: E501 - """CreateIndexRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - spec (IndexSpec): - - 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,) - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. [optional] if omitted the server will use the default value of "dense". # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.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, name, spec, *args, **kwargs) -> None: # noqa: E501 - """CreateIndexRequest - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - spec (IndexSpec): - - 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,) - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. [optional] if omitted the server will use the default value of "dense". # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/deletion_protection.py b/pinecone/core/openapi/db_control/model/deletion_protection.py deleted file mode 100644 index 24fc26f31..000000000 --- a/pinecone/core/openapi/db_control/model/deletion_protection.py +++ /dev/null @@ -1,276 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="DeletionProtection") - - -class DeletionProtection(ModelSimple): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("value",): {"DISABLED": "disabled", "ENABLED": "enabled"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = 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) -> None: - """DeletionProtection - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/manage-indexes#configure-deletion-protection) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 - - Keyword Args: - value (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/manage-indexes#configure-deletion-protection) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - value = "disabled" - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: - """DeletionProtection - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/manage-indexes#configure-deletion-protection) is enabled/disabled for the index. if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 - - Keyword Args: - value (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/manage-indexes#configure-deletion-protection) is enabled/disabled for the index. if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - value = "disabled" - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/openapi/db_control/model/error_response.py b/pinecone/core/openapi/db_control/model/error_response.py deleted file mode 100644 index b37c2e97c..000000000 --- a/pinecone/core/openapi/db_control/model/error_response.py +++ /dev/null @@ -1,280 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.error_response_error import ErrorResponseError - - globals()["ErrorResponseError"] = ErrorResponseError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ErrorResponse") - - -class ErrorResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "status": (int,), # noqa: E501 - "error": (ErrorResponseError,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "status": "status", # noqa: E501 - "error": "error", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], status, error, *args, **kwargs) -> T: # noqa: E501 - """ErrorResponse - a model defined in OpenAPI - - Args: - status (int): The HTTP status code of the error. - error (ErrorResponseError): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 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, status, error, *args, **kwargs) -> None: # noqa: E501 - """ErrorResponse - a model defined in OpenAPI - - Args: - status (int): The HTTP status code of the error. - error (ErrorResponseError): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/error_response_error.py b/pinecone/core/openapi/db_control/model/error_response_error.py deleted file mode 100644 index 613ccc4f5..000000000 --- a/pinecone/core/openapi/db_control/model/error_response_error.py +++ /dev/null @@ -1,299 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ErrorResponseError") - - -class ErrorResponseError(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("code",): { - "OK": "OK", - "UNKNOWN": "UNKNOWN", - "INVALID_ARGUMENT": "INVALID_ARGUMENT", - "DEADLINE_EXCEEDED": "DEADLINE_EXCEEDED", - "QUOTA_EXCEEDED": "QUOTA_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", - "FORBIDDEN": "FORBIDDEN", - "UNPROCESSABLE_ENTITY": "UNPROCESSABLE_ENTITY", - "PAYMENT_REQUIRED": "PAYMENT_REQUIRED", - } - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "code": "code", # noqa: E501 - "message": "message", # noqa: E501 - "details": "details", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], code, message, *args, **kwargs) -> T: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_list.py b/pinecone/core/openapi/db_control/model/index_list.py deleted file mode 100644 index ed6c08dfe..000000000 --- a/pinecone/core/openapi/db_control/model/index_list.py +++ /dev/null @@ -1,268 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.index_model import IndexModel - - globals()["IndexModel"] = IndexModel - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexList") - - -class IndexList(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "indexes": ([IndexModel],) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "indexes": "indexes" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """IndexList - 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,) - indexes ([IndexModel]): [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) -> None: # noqa: E501 - """IndexList - 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,) - indexes ([IndexModel]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_model.py b/pinecone/core/openapi/db_control/model/index_model.py deleted file mode 100644 index 3fe45763f..000000000 --- a/pinecone/core/openapi/db_control/model/index_model.py +++ /dev/null @@ -1,335 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection - from pinecone.core.openapi.db_control.model.index_model_spec import IndexModelSpec - from pinecone.core.openapi.db_control.model.index_model_status import IndexModelStatus - from pinecone.core.openapi.db_control.model.index_tags import IndexTags - from pinecone.core.openapi.db_control.model.model_index_embed import ModelIndexEmbed - - globals()["DeletionProtection"] = DeletionProtection - globals()["IndexModelSpec"] = IndexModelSpec - globals()["IndexModelStatus"] = IndexModelStatus - globals()["IndexTags"] = IndexTags - globals()["ModelIndexEmbed"] = ModelIndexEmbed - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexModel") - - -class IndexModel(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("name",): {"max_length": 45, "min_length": 1}, - ("dimension",): {"inclusive_maximum": 20000, "inclusive_minimum": 1}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "metric": (str,), # noqa: E501 - "host": (str,), # noqa: E501 - "spec": (IndexModelSpec,), # noqa: E501 - "status": (IndexModelStatus,), # noqa: E501 - "vector_type": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "deletion_protection": (DeletionProtection,), # noqa: E501 - "tags": (IndexTags,), # noqa: E501 - "embed": (ModelIndexEmbed,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "name": "name", # noqa: E501 - "metric": "metric", # noqa: E501 - "host": "host", # noqa: E501 - "spec": "spec", # noqa: E501 - "status": "status", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "deletion_protection": "deletion_protection", # noqa: E501 - "tags": "tags", # noqa: E501 - "embed": "embed", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], name, metric, host, spec, status, *args, **kwargs) -> T: # noqa: E501 - """IndexModel - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. - host (str): The URL address where the index is hosted. - spec (IndexModelSpec): - status (IndexModelStatus): - - Keyword Args: - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. defaults to "dense" # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - 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,) - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - embed (ModelIndexEmbed): [optional] # noqa: E501 - """ - - vector_type = kwargs.get("vector_type", "dense") - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.metric = metric - self.host = host - self.spec = spec - self.status = status - self.vector_type = vector_type - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - 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, host, spec, status, *args, **kwargs) -> None: # noqa: E501 - """IndexModel - a model defined in OpenAPI - - Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If the 'vector_type' is 'sparse', the metric must be 'dotproduct'. If the `vector_type` is `dense`, the metric defaults to 'cosine'. - host (str): The URL address where the index is hosted. - spec (IndexModelSpec): - status (IndexModelStatus): - - Keyword Args: - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. defaults to "dense" # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - 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,) - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - deletion_protection (DeletionProtection): [optional] # noqa: E501 - tags (IndexTags): [optional] # noqa: E501 - embed (ModelIndexEmbed): [optional] # noqa: E501 - """ - - vector_type = kwargs.get("vector_type", "dense") - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.metric = metric - self.host = host - self.spec = spec - self.status = status - self.vector_type = vector_type - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_model_spec.py b/pinecone/core/openapi/db_control/model/index_model_spec.py deleted file mode 100644 index b27ec0f8e..000000000 --- a/pinecone/core/openapi/db_control/model/index_model_spec.py +++ /dev/null @@ -1,274 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.pod_spec import PodSpec - from pinecone.core.openapi.db_control.model.serverless_spec import ServerlessSpec - - globals()["PodSpec"] = PodSpec - globals()["ServerlessSpec"] = ServerlessSpec - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexModelSpec") - - -class IndexModelSpec(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "pod": "pod", # noqa: E501 - "serverless": "serverless", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_model_status.py b/pinecone/core/openapi/db_control/model/index_model_status.py deleted file mode 100644 index 0128f22eb..000000000 --- a/pinecone/core/openapi/db_control/model/index_model_status.py +++ /dev/null @@ -1,283 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexModelStatus") - - -class IndexModelStatus(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("state",): { - "INITIALIZING": "Initializing", - "INITIALIZATIONFAILED": "InitializationFailed", - "SCALINGUP": "ScalingUp", - "SCALINGDOWN": "ScalingDown", - "SCALINGUPPODSIZE": "ScalingUpPodSize", - "SCALINGDOWNPODSIZE": "ScalingDownPodSize", - "TERMINATING": "Terminating", - "READY": "Ready", - } - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "ready": "ready", # noqa: E501 - "state": "state", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], ready, state, *args, **kwargs) -> T: # noqa: E501 - """IndexModelStatus - a model defined in OpenAPI - - Args: - ready (bool): - state (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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.ready = ready - self.state = state - 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, ready, state, *args, **kwargs) -> None: # noqa: E501 - """IndexModelStatus - a model defined in OpenAPI - - Args: - ready (bool): - state (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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.ready = ready - self.state = state - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_spec.py b/pinecone/core/openapi/db_control/model/index_spec.py deleted file mode 100644 index 6a8c4db55..000000000 --- a/pinecone/core/openapi/db_control/model/index_spec.py +++ /dev/null @@ -1,267 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.pod_spec import PodSpec - from pinecone.core.openapi.db_control.model.serverless_spec import ServerlessSpec - - globals()["PodSpec"] = PodSpec - globals()["ServerlessSpec"] = ServerlessSpec - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexSpec") - - -class IndexSpec(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - additional_properties_type = None - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "serverless": (ServerlessSpec,), # noqa: E501 - "pod": (PodSpec,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "serverless": "serverless", # noqa: E501 - "pod": "pod", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """IndexSpec - 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,) - serverless (ServerlessSpec): [optional] # noqa: E501 - pod (PodSpec): [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) -> None: # noqa: E501 - """IndexSpec - 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,) - serverless (ServerlessSpec): [optional] # noqa: E501 - pod (PodSpec): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/index_tags.py b/pinecone/core/openapi/db_control/model/index_tags.py deleted file mode 100644 index 6111f7b57..000000000 --- a/pinecone/core/openapi/db_control/model/index_tags.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexTags") - - -class IndexTags(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - 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 (str,) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 {} - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """IndexTags - 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,) - """ - - _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) -> None: # noqa: E501 - """IndexTags - 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,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/model_index_embed.py b/pinecone/core/openapi/db_control/model/model_index_embed.py deleted file mode 100644 index 624462a8b..000000000 --- a/pinecone/core/openapi/db_control/model/model_index_embed.py +++ /dev/null @@ -1,294 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ModelIndexEmbed") - - -class ModelIndexEmbed(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("metric",): {"COSINE": "cosine", "EUCLIDEAN": "euclidean", "DOTPRODUCT": "dotproduct"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("dimension",): {"inclusive_maximum": 20000, "inclusive_minimum": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "model": (str,), # noqa: E501 - "metric": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "vector_type": (str,), # noqa: E501 - "field_map": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "read_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "write_parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "metric": "metric", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - "field_map": "field_map", # noqa: E501 - "read_parameters": "read_parameters", # noqa: E501 - "write_parameters": "write_parameters", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, *args, **kwargs) -> T: # noqa: E501 - """ModelIndexEmbed - a model defined in OpenAPI - - Args: - model (str): The name of the embedding model used to create the index. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set. [optional] # noqa: E501 - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. [optional] if omitted the server will use the default value of "dense". # noqa: E501 - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that is embedded. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, *args, **kwargs) -> None: # noqa: E501 - """ModelIndexEmbed - a model defined in OpenAPI - - Args: - model (str): The name of the embedding model used to create the index. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'. If not specified, the metric will be defaulted according to the model. Cannot be updated once set. [optional] # noqa: E501 - dimension (int): The dimensions of the vectors to be inserted in the index. [optional] # noqa: E501 - vector_type (str): The index vector type. You can use 'dense' or 'sparse'. If 'dense', the vector dimension must be specified. If 'sparse', the vector dimension should not be specified. [optional] if omitted the server will use the default value of "dense". # noqa: E501 - field_map ({str: (bool, dict, float, int, list, str, none_type)}): Identifies the name of the text field from your document model that is embedded. [optional] # noqa: E501 - read_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The read parameters for the embedding model. [optional] # noqa: E501 - write_parameters ({str: (bool, dict, float, int, list, str, none_type)}): The write parameters for the embedding model. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/pod_spec.py b/pinecone/core/openapi/db_control/model/pod_spec.py deleted file mode 100644 index c430c6a39..000000000 --- a/pinecone/core/openapi/db_control/model/pod_spec.py +++ /dev/null @@ -1,308 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_control.model.pod_spec_metadata_config import ( - PodSpecMetadataConfig, - ) - - globals()["PodSpecMetadataConfig"] = PodSpecMetadataConfig - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="PodSpec") - - -class PodSpec(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("replicas",): {"inclusive_minimum": 1}, - ("shards",): {"inclusive_minimum": 1}, - ("pods",): {"inclusive_minimum": 1}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "pod_type": (str,), # noqa: E501 - "replicas": (int,), # noqa: E501 - "shards": (int,), # noqa: E501 - "pods": (int,), # noqa: E501 - "metadata_config": (PodSpecMetadataConfig,), # noqa: E501 - "source_collection": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "environment": "environment", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - "replicas": "replicas", # noqa: E501 - "shards": "shards", # noqa: E501 - "pods": "pods", # noqa: E501 - "metadata_config": "metadata_config", # noqa: E501 - "source_collection": "source_collection", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], environment, *args, **kwargs) -> T: # noqa: E501 - """PodSpec - a model defined in OpenAPI - - Args: - environment (str): The environment where the index is hosted. - - Keyword Args: - 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 - _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 number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change. [optional] if omitted the server will use the default value of 1. # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index. [optional] if omitted the server will use the default value of 1. # noqa: E501 - pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.' [optional] if omitted the server will use the default value of 1. # noqa: E501 - metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 - source_collection (str): The name of the collection to be used as the source for the index. [optional] # noqa: E501 - """ - - pod_type = kwargs.get("pod_type", "p1.x1") - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.environment = environment - self.pod_type = pod_type - 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) -> None: # noqa: E501 - """PodSpec - a model defined in OpenAPI - - Args: - environment (str): The environment where the index is hosted. - - Keyword Args: - 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 - _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 number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change. [optional] if omitted the server will use the default value of 1. # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index. [optional] if omitted the server will use the default value of 1. # noqa: E501 - pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.' [optional] if omitted the server will use the default value of 1. # noqa: E501 - metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 - source_collection (str): The name of the collection to be used as the source for the index. [optional] # noqa: E501 - """ - - pod_type = kwargs.get("pod_type", "p1.x1") - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.environment = environment - self.pod_type = pod_type - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py b/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py deleted file mode 100644 index 969471e6c..000000000 --- a/pinecone/core/openapi/db_control/model/pod_spec_metadata_config.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="PodSpecMetadataConfig") - - -class PodSpecMetadataConfig(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "indexed": "indexed" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 that 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 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) -> None: # 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 that 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/model/serverless_spec.py b/pinecone/core/openapi/db_control/model/serverless_spec.py deleted file mode 100644 index 58e39e487..000000000 --- a/pinecone/core/openapi/db_control/model/serverless_spec.py +++ /dev/null @@ -1,274 +0,0 @@ -""" -Pinecone Control Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ServerlessSpec") - - -class ServerlessSpec(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("cloud",): {"GCP": "gcp", "AWS": "aws", "AZURE": "azure"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "cloud": "cloud", # noqa: E501 - "region": "region", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], cloud, region, *args, **kwargs) -> T: # 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. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_control/models/__init__.py b/pinecone/core/openapi/db_control/models/__init__.py deleted file mode 100644 index fd82f1214..000000000 --- a/pinecone/core/openapi/db_control/models/__init__.py +++ /dev/null @@ -1,44 +0,0 @@ -# flake8: noqa - -# 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.openapi.db_control.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.openapi.db_control.model.collection_list import CollectionList -from pinecone.core.openapi.db_control.model.collection_model import CollectionModel -from pinecone.core.openapi.db_control.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.openapi.db_control.model.configure_index_request_embed import ( - ConfigureIndexRequestEmbed, -) -from pinecone.core.openapi.db_control.model.configure_index_request_spec import ( - ConfigureIndexRequestSpec, -) -from pinecone.core.openapi.db_control.model.configure_index_request_spec_pod import ( - ConfigureIndexRequestSpecPod, -) -from pinecone.core.openapi.db_control.model.create_collection_request import CreateCollectionRequest -from pinecone.core.openapi.db_control.model.create_index_for_model_request import ( - CreateIndexForModelRequest, -) -from pinecone.core.openapi.db_control.model.create_index_for_model_request_embed import ( - CreateIndexForModelRequestEmbed, -) -from pinecone.core.openapi.db_control.model.create_index_request import CreateIndexRequest -from pinecone.core.openapi.db_control.model.deletion_protection import DeletionProtection -from pinecone.core.openapi.db_control.model.error_response import ErrorResponse -from pinecone.core.openapi.db_control.model.error_response_error import ErrorResponseError -from pinecone.core.openapi.db_control.model.index_list import IndexList -from pinecone.core.openapi.db_control.model.index_model import IndexModel -from pinecone.core.openapi.db_control.model.index_model_spec import IndexModelSpec -from pinecone.core.openapi.db_control.model.index_model_status import IndexModelStatus -from pinecone.core.openapi.db_control.model.index_spec import IndexSpec -from pinecone.core.openapi.db_control.model.index_tags import IndexTags -from pinecone.core.openapi.db_control.model.model_index_embed import ModelIndexEmbed -from pinecone.core.openapi.db_control.model.pod_spec import PodSpec -from pinecone.core.openapi.db_control.model.pod_spec_metadata_config import PodSpecMetadataConfig -from pinecone.core.openapi.db_control.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/openapi/db_data/__init__.py b/pinecone/core/openapi/db_data/__init__.py deleted file mode 100644 index c878a5486..000000000 --- a/pinecone/core/openapi/db_data/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# flake8: noqa - -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.openapi_support.api_client import ApiClient - -# import Configuration -from pinecone.openapi_support.configuration import Configuration - -# import exceptions -from pinecone.openapi_support.exceptions import PineconeException -from pinecone.openapi_support.exceptions import PineconeApiAttributeError -from pinecone.openapi_support.exceptions import PineconeApiTypeError -from pinecone.openapi_support.exceptions import PineconeApiValueError -from pinecone.openapi_support.exceptions import PineconeApiKeyError -from pinecone.openapi_support.exceptions import PineconeApiException - -API_VERSION = "2025-01" diff --git a/pinecone/core/openapi/db_data/api/__init__.py b/pinecone/core/openapi/db_data/api/__init__.py deleted file mode 100644 index 9adc008c8..000000000 --- a/pinecone/core/openapi/db_data/api/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# 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.openapi.db_data.apis import BulkOperationsApi diff --git a/pinecone/core/openapi/db_data/api/bulk_operations_api.py b/pinecone/core/openapi/db_data/api/bulk_operations_api.py deleted file mode 100644 index fcfbac8aa..000000000 --- a/pinecone/core/openapi/db_data/api/bulk_operations_api.py +++ /dev/null @@ -1,576 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support import ApiClient, AsyncioApiClient -from pinecone.openapi_support.endpoint_utils import ( - ExtraOpenApiKwargsTypedDict, - KwargsWithOpenApiKwargDefaultsTypedDict, -) -from pinecone.openapi_support.endpoint import Endpoint as _Endpoint, ExtraOpenApiKwargsTypedDict -from pinecone.openapi_support.asyncio_endpoint import AsyncioEndpoint as _AsyncioEndpoint -from pinecone.openapi_support.model_utils import ( # noqa: F401 - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.openapi.db_data.model.import_model import ImportModel -from pinecone.core.openapi.db_data.model.list_imports_response import ListImportsResponse -from pinecone.core.openapi.db_data.model.rpc_status import RpcStatus -from pinecone.core.openapi.db_data.model.start_import_request import StartImportRequest -from pinecone.core.openapi.db_data.model.start_import_response import StartImportResponse - - -class BulkOperationsApi: - """NOTE: This class is @generated using OpenAPI. - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def __cancel_bulk_import(self, id, **kwargs: ExtraOpenApiKwargsTypedDict): - """Cancel an import # noqa: E501 - - Cancel an import operation if it is not yet finished. It has no effect if the operation is already finished. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.cancel_bulk_import(id, async_req=True) - >>> result = thread.get() - - Args: - id (str): Unique identifier for the import operation. - - 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. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["id"] = id - return self.call_with_http_info(**kwargs) - - self.cancel_bulk_import = _Endpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports/{id}", - "operation_id": "cancel_bulk_import", - "http_method": "DELETE", - "servers": None, - }, - params_map={ - "all": ["id"], - "required": ["id"], - "nullable": [], - "enum": [], - "validation": ["id"], - }, - root_map={ - "validations": {("id",): {"max_length": 1000, "min_length": 1}}, - "allowed_values": {}, - "openapi_types": {"id": (str,)}, - "attribute_map": {"id": "id"}, - "location_map": {"id": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__cancel_bulk_import, - ) - - def __describe_bulk_import(self, id, **kwargs: ExtraOpenApiKwargsTypedDict): - """Describe an import # noqa: E501 - - Return details of a specific import operation. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.describe_bulk_import(id, async_req=True) - >>> result = thread.get() - - Args: - id (str): Unique identifier for the import operation. - - 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. - async_req (bool): execute request asynchronously - - Returns: - ImportModel - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["id"] = id - return self.call_with_http_info(**kwargs) - - self.describe_bulk_import = _Endpoint( - settings={ - "response_type": (ImportModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports/{id}", - "operation_id": "describe_bulk_import", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["id"], - "required": ["id"], - "nullable": [], - "enum": [], - "validation": ["id"], - }, - root_map={ - "validations": {("id",): {"max_length": 1000, "min_length": 1}}, - "allowed_values": {}, - "openapi_types": {"id": (str,)}, - "attribute_map": {"id": "id"}, - "location_map": {"id": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__describe_bulk_import, - ) - - def __list_bulk_imports(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """List imports # noqa: E501 - - List all recent and ongoing import operations. By default, this returns up to 100 imports per page. If the `limit` parameter is set, `list` returns up to that number of imports instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of imports. When the response does not include a `pagination_token`, there are no more imports to return. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_bulk_imports(async_req=True) - >>> result = thread.get() - - - Keyword Args: - limit (int): Max number of operations to return per page. [optional] - pagination_token (str): Pagination token to continue a previous listing operation. [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. - async_req (bool): execute request asynchronously - - Returns: - ListImportsResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - return self.call_with_http_info(**kwargs) - - self.list_bulk_imports = _Endpoint( - settings={ - "response_type": (ListImportsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports", - "operation_id": "list_bulk_imports", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["limit", "pagination_token"], - "required": [], - "nullable": [], - "enum": [], - "validation": ["limit"], - }, - root_map={ - "validations": {("limit",): {"inclusive_maximum": 100, "inclusive_minimum": 1}}, - "allowed_values": {}, - "openapi_types": {"limit": (int,), "pagination_token": (str,)}, - "attribute_map": {"limit": "limit", "pagination_token": "paginationToken"}, - "location_map": {"limit": "query", "pagination_token": "query"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__list_bulk_imports, - ) - - def __start_bulk_import(self, start_import_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Start import # noqa: E501 - - Start an asynchronous import of vectors from object storage into an index. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.start_bulk_import(start_import_request, async_req=True) - >>> result = thread.get() - - Args: - start_import_request (StartImportRequest): - - 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. - async_req (bool): execute request asynchronously - - Returns: - StartImportResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["start_import_request"] = start_import_request - return self.call_with_http_info(**kwargs) - - self.start_bulk_import = _Endpoint( - settings={ - "response_type": (StartImportResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports", - "operation_id": "start_bulk_import", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["start_import_request"], - "required": ["start_import_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"start_import_request": (StartImportRequest,)}, - "attribute_map": {}, - "location_map": {"start_import_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__start_bulk_import, - ) - - -class AsyncioBulkOperationsApi: - """NOTE: This class is @generated using OpenAPI - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = AsyncioApiClient() - self.api_client = api_client - - async def __cancel_bulk_import(self, id, **kwargs): - """Cancel an import # noqa: E501 - - Cancel an import operation if it is not yet finished. It has no effect if the operation is already finished. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - - - Args: - id (str): Unique identifier for the import operation. - - 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. - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - """ - self._process_openapi_kwargs(kwargs) - kwargs["id"] = id - return await self.call_with_http_info(**kwargs) - - self.cancel_bulk_import = _AsyncioEndpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports/{id}", - "operation_id": "cancel_bulk_import", - "http_method": "DELETE", - "servers": None, - }, - params_map={ - "all": ["id"], - "required": ["id"], - "nullable": [], - "enum": [], - "validation": ["id"], - }, - root_map={ - "validations": {("id",): {"max_length": 1000, "min_length": 1}}, - "allowed_values": {}, - "openapi_types": {"id": (str,)}, - "attribute_map": {"id": "id"}, - "location_map": {"id": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__cancel_bulk_import, - ) - - async def __describe_bulk_import(self, id, **kwargs): - """Describe an import # noqa: E501 - - Return details of a specific import operation. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - - - Args: - id (str): Unique identifier for the import operation. - - 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. - - Returns: - ImportModel - """ - self._process_openapi_kwargs(kwargs) - kwargs["id"] = id - return await self.call_with_http_info(**kwargs) - - self.describe_bulk_import = _AsyncioEndpoint( - settings={ - "response_type": (ImportModel,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports/{id}", - "operation_id": "describe_bulk_import", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["id"], - "required": ["id"], - "nullable": [], - "enum": [], - "validation": ["id"], - }, - root_map={ - "validations": {("id",): {"max_length": 1000, "min_length": 1}}, - "allowed_values": {}, - "openapi_types": {"id": (str,)}, - "attribute_map": {"id": "id"}, - "location_map": {"id": "path"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__describe_bulk_import, - ) - - async def __list_bulk_imports(self, **kwargs): - """List imports # noqa: E501 - - List all recent and ongoing import operations. By default, this returns up to 100 imports per page. If the `limit` parameter is set, `list` returns up to that number of imports instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of imports. When the response does not include a `pagination_token`, there are no more imports to return. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - - - - Keyword Args: - limit (int): Max number of operations to return per page. [optional] - pagination_token (str): Pagination token to continue a previous listing operation. [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. - - Returns: - ListImportsResponse - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.list_bulk_imports = _AsyncioEndpoint( - settings={ - "response_type": (ListImportsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports", - "operation_id": "list_bulk_imports", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["limit", "pagination_token"], - "required": [], - "nullable": [], - "enum": [], - "validation": ["limit"], - }, - root_map={ - "validations": {("limit",): {"inclusive_maximum": 100, "inclusive_minimum": 1}}, - "allowed_values": {}, - "openapi_types": {"limit": (int,), "pagination_token": (str,)}, - "attribute_map": {"limit": "limit", "pagination_token": "paginationToken"}, - "location_map": {"limit": "query", "pagination_token": "query"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__list_bulk_imports, - ) - - async def __start_bulk_import(self, start_import_request, **kwargs): - """Start import # noqa: E501 - - Start an asynchronous import of vectors from object storage into an index. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). # noqa: E501 - - - Args: - start_import_request (StartImportRequest): - - 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. - - Returns: - StartImportResponse - """ - self._process_openapi_kwargs(kwargs) - kwargs["start_import_request"] = start_import_request - return await self.call_with_http_info(**kwargs) - - self.start_bulk_import = _AsyncioEndpoint( - settings={ - "response_type": (StartImportResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/bulk/imports", - "operation_id": "start_bulk_import", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["start_import_request"], - "required": ["start_import_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"start_import_request": (StartImportRequest,)}, - "attribute_map": {}, - "location_map": {"start_import_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__start_bulk_import, - ) diff --git a/pinecone/core/openapi/db_data/api/vector_operations_api.py b/pinecone/core/openapi/db_data/api/vector_operations_api.py deleted file mode 100644 index 22bb47c3f..000000000 --- a/pinecone/core/openapi/db_data/api/vector_operations_api.py +++ /dev/null @@ -1,1298 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support import ApiClient, AsyncioApiClient -from pinecone.openapi_support.endpoint_utils import ( - ExtraOpenApiKwargsTypedDict, - KwargsWithOpenApiKwargDefaultsTypedDict, -) -from pinecone.openapi_support.endpoint import Endpoint as _Endpoint, ExtraOpenApiKwargsTypedDict -from pinecone.openapi_support.asyncio_endpoint import AsyncioEndpoint as _AsyncioEndpoint -from pinecone.openapi_support.model_utils import ( # noqa: F401 - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.openapi.db_data.model.delete_request import DeleteRequest -from pinecone.core.openapi.db_data.model.describe_index_stats_request import ( - DescribeIndexStatsRequest, -) -from pinecone.core.openapi.db_data.model.fetch_response import FetchResponse -from pinecone.core.openapi.db_data.model.index_description import IndexDescription -from pinecone.core.openapi.db_data.model.list_response import ListResponse -from pinecone.core.openapi.db_data.model.query_request import QueryRequest -from pinecone.core.openapi.db_data.model.query_response import QueryResponse -from pinecone.core.openapi.db_data.model.rpc_status import RpcStatus -from pinecone.core.openapi.db_data.model.search_records_request import SearchRecordsRequest -from pinecone.core.openapi.db_data.model.search_records_response import SearchRecordsResponse -from pinecone.core.openapi.db_data.model.update_request import UpdateRequest -from pinecone.core.openapi.db_data.model.upsert_record import UpsertRecord -from pinecone.core.openapi.db_data.model.upsert_request import UpsertRequest -from pinecone.core.openapi.db_data.model.upsert_response import UpsertResponse - - -class VectorOperationsApi: - """NOTE: This class is @generated using OpenAPI. - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def __delete_vectors(self, delete_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Delete vectors # noqa: E501 - - Delete vectors, by id, from a single namespace. For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). # 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_vectors(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. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["delete_request"] = delete_request - return self.call_with_http_info(**kwargs) - - self.delete_vectors = _Endpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/delete", - "operation_id": "delete_vectors", - "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_vectors, - ) - - def __describe_index_stats( - self, describe_index_stats_request, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Get index stats # noqa: E501 - - Return statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> 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. - async_req (bool): execute request asynchronously - - Returns: - IndexDescription - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["describe_index_stats_request"] = describe_index_stats_request - return self.call_with_http_info(**kwargs) - - self.describe_index_stats = _Endpoint( - settings={ - "response_type": (IndexDescription,), - "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, - ) - - def __fetch_vectors(self, ids, **kwargs: ExtraOpenApiKwargsTypedDict): - """Fetch vectors # noqa: E501 - - Look up and return vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. For guidance and examples, see [Fetch data](https://docs.pinecone.io/guides/data/fetch-data). # 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_vectors(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. - async_req (bool): execute request asynchronously - - Returns: - FetchResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["ids"] = ids - return self.call_with_http_info(**kwargs) - - self.fetch_vectors = _Endpoint( - settings={ - "response_type": (FetchResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/fetch", - "operation_id": "fetch_vectors", - "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_vectors, - ) - - def __list_vectors(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """List vector IDs # noqa: E501 - - List the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. This returns up to 100 IDs at a time by default in sorted order (bitwise \"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list` is supported only for serverless indexes. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.list_vectors(async_req=True) - >>> result = thread.get() - - - Keyword Args: - prefix (str): The vector IDs to fetch. Does not accept values containing spaces. [optional] - limit (int): Max number of IDs to return per page. [optional] - pagination_token (str): Pagination token to continue a previous listing operation. [optional] - 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. - async_req (bool): execute request asynchronously - - Returns: - ListResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - return self.call_with_http_info(**kwargs) - - self.list_vectors = _Endpoint( - settings={ - "response_type": (ListResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/list", - "operation_id": "list_vectors", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["prefix", "limit", "pagination_token", "namespace"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "prefix": (str,), - "limit": (int,), - "pagination_token": (str,), - "namespace": (str,), - }, - "attribute_map": { - "prefix": "prefix", - "limit": "limit", - "pagination_token": "paginationToken", - "namespace": "namespace", - }, - "location_map": { - "prefix": "query", - "limit": "query", - "pagination_token": "query", - "namespace": "query", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__list_vectors, - ) - - def __query_vectors(self, query_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Query vectors # noqa: E501 - - Search a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. For guidance and examples, see [Query data](https://docs.pinecone.io/guides/data/query-data). # 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_vectors(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. - async_req (bool): execute request asynchronously - - Returns: - QueryResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["query_request"] = query_request - return self.call_with_http_info(**kwargs) - - self.query_vectors = _Endpoint( - settings={ - "response_type": (QueryResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/query", - "operation_id": "query_vectors", - "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_vectors, - ) - - def __search_records_namespace( - self, namespace, search_records_request, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Search a namespace # noqa: E501 - - This operation converts a query to a vector embedding and then searches a namespace using the embedding. It returns the most similar records in the namespace, along with their similarity scores. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.search_records_namespace(namespace, search_records_request, async_req=True) - >>> result = thread.get() - - Args: - namespace (str): The namespace to search. - search_records_request (SearchRecordsRequest): - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - async_req (bool): execute request asynchronously - - Returns: - SearchRecordsResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["namespace"] = namespace - kwargs["search_records_request"] = search_records_request - return self.call_with_http_info(**kwargs) - - self.search_records_namespace = _Endpoint( - settings={ - "response_type": (SearchRecordsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/records/namespaces/{namespace}/search", - "operation_id": "search_records_namespace", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["namespace", "search_records_request"], - "required": ["namespace", "search_records_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "namespace": (str,), - "search_records_request": (SearchRecordsRequest,), - }, - "attribute_map": {"namespace": "namespace"}, - "location_map": {"namespace": "path", "search_records_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__search_records_namespace, - ) - - def __update_vector(self, update_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Update a vector # noqa: E501 - - Update a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). # 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_vector(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. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["update_request"] = update_request - return self.call_with_http_info(**kwargs) - - self.update_vector = _Endpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/update", - "operation_id": "update_vector", - "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_vector, - ) - - def __upsert_records_namespace( - self, namespace, upsert_record, **kwargs: ExtraOpenApiKwargsTypedDict - ): - """Upsert records into a namespace # noqa: E501 - - This operation converts input data to vector embeddings and then upserts the embeddings into a namespace. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.upsert_records_namespace(namespace, upsert_record, async_req=True) - >>> result = thread.get() - - Args: - namespace (str): The namespace to upsert records into. - upsert_record ([UpsertRecord]): - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - async_req (bool): execute request asynchronously - - Returns: - None - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["namespace"] = namespace - kwargs["upsert_record"] = upsert_record - return self.call_with_http_info(**kwargs) - - self.upsert_records_namespace = _Endpoint( - settings={ - "response_type": None, - "auth": ["ApiKeyAuth"], - "endpoint_path": "/records/namespaces/{namespace}/upsert", - "operation_id": "upsert_records_namespace", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["namespace", "upsert_record"], - "required": ["namespace", "upsert_record"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"namespace": (str,), "upsert_record": ([UpsertRecord],)}, - "attribute_map": {"namespace": "namespace"}, - "location_map": {"namespace": "path", "upsert_record": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/x-ndjson"]}, - api_client=api_client, - callable=__upsert_records_namespace, - ) - - def __upsert_vectors(self, upsert_request, **kwargs: ExtraOpenApiKwargsTypedDict): - """Upsert vectors # noqa: E501 - - Write vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. For guidance and examples, see [Upsert data](https://docs.pinecone.io/guides/data/upsert-data). # 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_vectors(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. - async_req (bool): execute request asynchronously - - Returns: - UpsertResponse - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - kwargs["upsert_request"] = upsert_request - return self.call_with_http_info(**kwargs) - - self.upsert_vectors = _Endpoint( - settings={ - "response_type": (UpsertResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/upsert", - "operation_id": "upsert_vectors", - "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_vectors, - ) - - -class AsyncioVectorOperationsApi: - """NOTE: This class is @generated using OpenAPI - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = AsyncioApiClient() - self.api_client = api_client - - async def __delete_vectors(self, delete_request, **kwargs): - """Delete vectors # noqa: E501 - - Delete vectors, by id, from a single namespace. For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). # noqa: E501 - - - 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. - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - """ - self._process_openapi_kwargs(kwargs) - kwargs["delete_request"] = delete_request - return await self.call_with_http_info(**kwargs) - - self.delete_vectors = _AsyncioEndpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/delete", - "operation_id": "delete_vectors", - "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_vectors, - ) - - async def __describe_index_stats(self, describe_index_stats_request, **kwargs): - """Get index stats # noqa: E501 - - Return statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. # noqa: E501 - - - 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. - - Returns: - IndexDescription - """ - self._process_openapi_kwargs(kwargs) - kwargs["describe_index_stats_request"] = describe_index_stats_request - return await self.call_with_http_info(**kwargs) - - self.describe_index_stats = _AsyncioEndpoint( - settings={ - "response_type": (IndexDescription,), - "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, - ) - - async def __fetch_vectors(self, ids, **kwargs): - """Fetch vectors # noqa: E501 - - Look up and return vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. For guidance and examples, see [Fetch data](https://docs.pinecone.io/guides/data/fetch-data). # noqa: E501 - - - 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. - - Returns: - FetchResponse - """ - self._process_openapi_kwargs(kwargs) - kwargs["ids"] = ids - return await self.call_with_http_info(**kwargs) - - self.fetch_vectors = _AsyncioEndpoint( - settings={ - "response_type": (FetchResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/fetch", - "operation_id": "fetch_vectors", - "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_vectors, - ) - - async def __list_vectors(self, **kwargs): - """List vector IDs # noqa: E501 - - List the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. This returns up to 100 IDs at a time by default in sorted order (bitwise \"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list` is supported only for serverless indexes. # noqa: E501 - - - - Keyword Args: - prefix (str): The vector IDs to fetch. Does not accept values containing spaces. [optional] - limit (int): Max number of IDs to return per page. [optional] - pagination_token (str): Pagination token to continue a previous listing operation. [optional] - 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. - - Returns: - ListResponse - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.list_vectors = _AsyncioEndpoint( - settings={ - "response_type": (ListResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/list", - "operation_id": "list_vectors", - "http_method": "GET", - "servers": None, - }, - params_map={ - "all": ["prefix", "limit", "pagination_token", "namespace"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "prefix": (str,), - "limit": (int,), - "pagination_token": (str,), - "namespace": (str,), - }, - "attribute_map": { - "prefix": "prefix", - "limit": "limit", - "pagination_token": "paginationToken", - "namespace": "namespace", - }, - "location_map": { - "prefix": "query", - "limit": "query", - "pagination_token": "query", - "namespace": "query", - }, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": []}, - api_client=api_client, - callable=__list_vectors, - ) - - async def __query_vectors(self, query_request, **kwargs): - """Query vectors # noqa: E501 - - Search a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. For guidance and examples, see [Query data](https://docs.pinecone.io/guides/data/query-data). # noqa: E501 - - - 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. - - Returns: - QueryResponse - """ - self._process_openapi_kwargs(kwargs) - kwargs["query_request"] = query_request - return await self.call_with_http_info(**kwargs) - - self.query_vectors = _AsyncioEndpoint( - settings={ - "response_type": (QueryResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/query", - "operation_id": "query_vectors", - "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_vectors, - ) - - async def __search_records_namespace(self, namespace, search_records_request, **kwargs): - """Search a namespace # noqa: E501 - - This operation converts a query to a vector embedding and then searches a namespace using the embedding. It returns the most similar records in the namespace, along with their similarity scores. # noqa: E501 - - - Args: - namespace (str): The namespace to search. - search_records_request (SearchRecordsRequest): - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - - Returns: - SearchRecordsResponse - """ - self._process_openapi_kwargs(kwargs) - kwargs["namespace"] = namespace - kwargs["search_records_request"] = search_records_request - return await self.call_with_http_info(**kwargs) - - self.search_records_namespace = _AsyncioEndpoint( - settings={ - "response_type": (SearchRecordsResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/records/namespaces/{namespace}/search", - "operation_id": "search_records_namespace", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["namespace", "search_records_request"], - "required": ["namespace", "search_records_request"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": { - "namespace": (str,), - "search_records_request": (SearchRecordsRequest,), - }, - "attribute_map": {"namespace": "namespace"}, - "location_map": {"namespace": "path", "search_records_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__search_records_namespace, - ) - - async def __update_vector(self, update_request, **kwargs): - """Update a vector # noqa: E501 - - Update a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). # noqa: E501 - - - 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. - - Returns: - {str: (bool, dict, float, int, list, str, none_type)} - """ - self._process_openapi_kwargs(kwargs) - kwargs["update_request"] = update_request - return await self.call_with_http_info(**kwargs) - - self.update_vector = _AsyncioEndpoint( - settings={ - "response_type": ({str: (bool, dict, float, int, list, str, none_type)},), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/update", - "operation_id": "update_vector", - "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_vector, - ) - - async def __upsert_records_namespace(self, namespace, upsert_record, **kwargs): - """Upsert records into a namespace # noqa: E501 - - This operation converts input data to vector embeddings and then upserts the embeddings into a namespace. # noqa: E501 - - - Args: - namespace (str): The namespace to upsert records into. - upsert_record ([UpsertRecord]): - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - - Returns: - None - """ - self._process_openapi_kwargs(kwargs) - kwargs["namespace"] = namespace - kwargs["upsert_record"] = upsert_record - return await self.call_with_http_info(**kwargs) - - self.upsert_records_namespace = _AsyncioEndpoint( - settings={ - "response_type": None, - "auth": ["ApiKeyAuth"], - "endpoint_path": "/records/namespaces/{namespace}/upsert", - "operation_id": "upsert_records_namespace", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["namespace", "upsert_record"], - "required": ["namespace", "upsert_record"], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"namespace": (str,), "upsert_record": ([UpsertRecord],)}, - "attribute_map": {"namespace": "namespace"}, - "location_map": {"namespace": "path", "upsert_record": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/x-ndjson"]}, - api_client=api_client, - callable=__upsert_records_namespace, - ) - - async def __upsert_vectors(self, upsert_request, **kwargs): - """Upsert vectors # noqa: E501 - - Write vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. For guidance and examples, see [Upsert data](https://docs.pinecone.io/guides/data/upsert-data). # noqa: E501 - - - 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. - - Returns: - UpsertResponse - """ - self._process_openapi_kwargs(kwargs) - kwargs["upsert_request"] = upsert_request - return await self.call_with_http_info(**kwargs) - - self.upsert_vectors = _AsyncioEndpoint( - settings={ - "response_type": (UpsertResponse,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/vectors/upsert", - "operation_id": "upsert_vectors", - "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_vectors, - ) diff --git a/pinecone/core/openapi/db_data/apis/__init__.py b/pinecone/core/openapi/db_data/apis/__init__.py deleted file mode 100644 index 3d7112fdc..000000000 --- a/pinecone/core/openapi/db_data/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.bulk_operations_api import BulkOperationsApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from pinecone.core.openapi.db_data.api.bulk_operations_api import BulkOperationsApi -from pinecone.core.openapi.db_data.api.vector_operations_api import VectorOperationsApi diff --git a/pinecone/core/openapi/db_data/model/__init__.py b/pinecone/core/openapi/db_data/model/__init__.py deleted file mode 100644 index cfe32b784..000000000 --- a/pinecone/core/openapi/db_data/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/openapi/db_data/model/delete_request.py b/pinecone/core/openapi/db_data/model/delete_request.py deleted file mode 100644 index 79e399051..000000000 --- a/pinecone/core/openapi/db_data/model/delete_request.py +++ /dev/null @@ -1,272 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="DeleteRequest") - - -class DeleteRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {("ids",): {}} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "ids": "ids", # noqa: E501 - "delete_all": "deleteAll", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "filter": "filter", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _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) -> None: # 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, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/describe_index_stats_request.py b/pinecone/core/openapi/db_data/model/describe_index_stats_request.py deleted file mode 100644 index 769f8dcbd..000000000 --- a/pinecone/core/openapi/db_data/model/describe_index_stats_request.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="DescribeIndexStatsRequest") - - -class DescribeIndexStatsRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "filter": "filter" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _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) -> None: # 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, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/fetch_response.py b/pinecone/core/openapi/db_data/model/fetch_response.py deleted file mode 100644 index 6a918dbc4..000000000 --- a/pinecone/core/openapi/db_data/model/fetch_response.py +++ /dev/null @@ -1,278 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.usage import Usage - from pinecone.core.openapi.db_data.model.vector import Vector - - globals()["Usage"] = Usage - globals()["Vector"] = Vector - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="FetchResponse") - - -class FetchResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "usage": (Usage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "vectors": "vectors", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 - usage (Usage): [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) -> None: # 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 - usage (Usage): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/hit.py b/pinecone/core/openapi/db_data/model/hit.py deleted file mode 100644 index 8af69b372..000000000 --- a/pinecone/core/openapi/db_data/model/hit.py +++ /dev/null @@ -1,278 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Hit") - - -class Hit(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "_id": (str,), # noqa: E501 - "_score": (float,), # noqa: E501 - "fields": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "_id": "_id", # noqa: E501 - "_score": "_score", # noqa: E501 - "fields": "fields", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], _id, _score, fields, *args, **kwargs) -> T: # noqa: E501 - """Hit - a model defined in OpenAPI - - Args: - _id (str): The record id of the search hit. - _score (float): The similarity score of the returned record. - fields ({str: (bool, dict, float, int, list, str, none_type)}): The selected record fields associated with the search hit. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self._id = _id - self._score = _score - self.fields = fields - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, _id, _score, fields, *args, **kwargs) -> None: # noqa: E501 - """Hit - a model defined in OpenAPI - - Args: - _id (str): The record id of the search hit. - _score (float): The similarity score of the returned record. - fields ({str: (bool, dict, float, int, list, str, none_type)}): The selected record fields associated with the search hit. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self._id = _id - self._score = _score - self.fields = fields - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/import_error_mode.py b/pinecone/core/openapi/db_data/model/import_error_mode.py deleted file mode 100644 index dd8a0e71b..000000000 --- a/pinecone/core/openapi/db_data/model/import_error_mode.py +++ /dev/null @@ -1,262 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ImportErrorMode") - - -class ImportErrorMode(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("on_error",): {"ABORT": "abort", "CONTINUE": "continue"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "on_error": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "on_error": "onError" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ImportErrorMode - 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,) - on_error (str): Indicates how to respond to errors during the import process. [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) -> None: # noqa: E501 - """ImportErrorMode - 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,) - on_error (str): Indicates how to respond to errors during the import process. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/import_model.py b/pinecone/core/openapi/db_data/model/import_model.py deleted file mode 100644 index d1d4589f3..000000000 --- a/pinecone/core/openapi/db_data/model/import_model.py +++ /dev/null @@ -1,299 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ImportModel") - - -class ImportModel(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("status",): { - "PENDING": "Pending", - "INPROGRESS": "InProgress", - "FAILED": "Failed", - "COMPLETED": "Completed", - "CANCELLED": "Cancelled", - } - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("id",): {"max_length": 1000, "min_length": 1}, - ("percent_complete",): {"inclusive_maximum": 100.0, "inclusive_minimum": 0.0}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "id": (str,), # noqa: E501 - "uri": (str,), # noqa: E501 - "status": (str,), # noqa: E501 - "created_at": (datetime,), # noqa: E501 - "finished_at": (datetime,), # noqa: E501 - "percent_complete": (float,), # noqa: E501 - "records_imported": (int,), # noqa: E501 - "error": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "id": "id", # noqa: E501 - "uri": "uri", # noqa: E501 - "status": "status", # noqa: E501 - "created_at": "createdAt", # noqa: E501 - "finished_at": "finishedAt", # noqa: E501 - "percent_complete": "percentComplete", # noqa: E501 - "records_imported": "recordsImported", # noqa: E501 - "error": "error", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ImportModel - 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,) - id (str): Unique identifier for the import operation. [optional] # noqa: E501 - uri (str): The URI from where the data is imported. [optional] # noqa: E501 - status (str): The status of the operation. [optional] # noqa: E501 - created_at (datetime): The start time of the import operation. [optional] # noqa: E501 - finished_at (datetime): The end time of the import operation. [optional] # noqa: E501 - percent_complete (float): The progress made by the operation, as a percentage. [optional] # noqa: E501 - records_imported (int): The number of records successfully imported. [optional] # noqa: E501 - error (str): The error message if the import process failed. [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) -> None: # noqa: E501 - """ImportModel - 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,) - id (str): Unique identifier for the import operation. [optional] # noqa: E501 - uri (str): The URI from where the data is imported. [optional] # noqa: E501 - status (str): The status of the operation. [optional] # noqa: E501 - created_at (datetime): The start time of the import operation. [optional] # noqa: E501 - finished_at (datetime): The end time of the import operation. [optional] # noqa: E501 - percent_complete (float): The progress made by the operation, as a percentage. [optional] # noqa: E501 - records_imported (int): The number of records successfully imported. [optional] # noqa: E501 - error (str): The error message if the import process failed. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/index_description.py b/pinecone/core/openapi/db_data/model/index_description.py deleted file mode 100644 index 1bbc7198d..000000000 --- a/pinecone/core/openapi/db_data/model/index_description.py +++ /dev/null @@ -1,288 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.namespace_summary import NamespaceSummary - - globals()["NamespaceSummary"] = NamespaceSummary - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="IndexDescription") - - -class IndexDescription(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "metric": (str,), # noqa: E501 - "vector_type": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "namespaces": "namespaces", # noqa: E501 - "dimension": "dimension", # noqa: E501 - "index_fullness": "indexFullness", # noqa: E501 - "total_vector_count": "totalVectorCount", # noqa: E501 - "metric": "metric", # noqa: E501 - "vector_type": "vectorType", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """IndexDescription - 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. Not specified if `sparse` index. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/2024-10/control-plane/describe_index). [optional] # noqa: E501 - total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed [optional] # noqa: E501 - metric (str): The metric used to measure similarity. [optional] # noqa: E501 - vector_type (str): The type of vectors stored in the index. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _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) -> None: # noqa: E501 - """IndexDescription - 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. Not specified if `sparse` index. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/2024-10/control-plane/describe_index). [optional] # noqa: E501 - total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed [optional] # noqa: E501 - metric (str): The metric used to measure similarity. [optional] # noqa: E501 - vector_type (str): The type of vectors stored in the index. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/list_imports_response.py b/pinecone/core/openapi/db_data/model/list_imports_response.py deleted file mode 100644 index 1b485e8b4..000000000 --- a/pinecone/core/openapi/db_data/model/list_imports_response.py +++ /dev/null @@ -1,274 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.import_model import ImportModel - from pinecone.core.openapi.db_data.model.pagination import Pagination - - globals()["ImportModel"] = ImportModel - globals()["Pagination"] = Pagination - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ListImportsResponse") - - -class ListImportsResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "data": ([ImportModel],), # noqa: E501 - "pagination": (Pagination,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "data": "data", # noqa: E501 - "pagination": "pagination", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ListImportsResponse - 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,) - data ([ImportModel]): [optional] # noqa: E501 - pagination (Pagination): [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) -> None: # noqa: E501 - """ListImportsResponse - 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,) - data ([ImportModel]): [optional] # noqa: E501 - pagination (Pagination): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/list_item.py b/pinecone/core/openapi/db_data/model/list_item.py deleted file mode 100644 index ad58c600f..000000000 --- a/pinecone/core/openapi/db_data/model/list_item.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ListItem") - - -class ListItem(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "id": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "id": "id" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ListItem - 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,) - id (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 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) -> None: # noqa: E501 - """ListItem - 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,) - id (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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/list_response.py b/pinecone/core/openapi/db_data/model/list_response.py deleted file mode 100644 index 4a8d0c5e3..000000000 --- a/pinecone/core/openapi/db_data/model/list_response.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.list_item import ListItem - from pinecone.core.openapi.db_data.model.pagination import Pagination - from pinecone.core.openapi.db_data.model.usage import Usage - - globals()["ListItem"] = ListItem - globals()["Pagination"] = Pagination - globals()["Usage"] = Usage - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ListResponse") - - -class ListResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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": ([ListItem],), # noqa: E501 - "pagination": (Pagination,), # noqa: E501 - "namespace": (str,), # noqa: E501 - "usage": (Usage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "vectors": "vectors", # noqa: E501 - "pagination": "pagination", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """ListResponse - 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 ([ListItem]): [optional] # noqa: E501 - pagination (Pagination): [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) - _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) -> None: # noqa: E501 - """ListResponse - 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 ([ListItem]): [optional] # noqa: E501 - pagination (Pagination): [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) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/namespace_summary.py b/pinecone/core/openapi/db_data/model/namespace_summary.py deleted file mode 100644 index a2ba425a5..000000000 --- a/pinecone/core/openapi/db_data/model/namespace_summary.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="NamespaceSummary") - - -class NamespaceSummary(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "vector_count": "vectorCount" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/pagination.py b/pinecone/core/openapi/db_data/model/pagination.py deleted file mode 100644 index f93898c88..000000000 --- a/pinecone/core/openapi/db_data/model/pagination.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Pagination") - - -class Pagination(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "next": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "next": "next" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """Pagination - 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,) - next (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 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) -> None: # noqa: E501 - """Pagination - 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,) - next (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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/protobuf_any.py b/pinecone/core/openapi/db_data/model/protobuf_any.py deleted file mode 100644 index 6e2c3c54e..000000000 --- a/pinecone/core/openapi/db_data/model/protobuf_any.py +++ /dev/null @@ -1,264 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ProtobufAny") - - -class ProtobufAny(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "type_url": "typeUrl", # noqa: E501 - "value": "value", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/protobuf_null_value.py b/pinecone/core/openapi/db_data/model/protobuf_null_value.py deleted file mode 100644 index 02ac25b85..000000000 --- a/pinecone/core/openapi/db_data/model/protobuf_null_value.py +++ /dev/null @@ -1,276 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ProtobufNullValue") - - -class ProtobufNullValue(ModelSimple): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("value",): {"NULL_VALUE": "NULL_VALUE"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = 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) -> None: - """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`.. 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`.. 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", ()) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - 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", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: - """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`. 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`. 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) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - 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", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/openapi/db_data/model/query_request.py b/pinecone/core/openapi/db_data/model/query_request.py deleted file mode 100644 index 23763e6d4..000000000 --- a/pinecone/core/openapi/db_data/model/query_request.py +++ /dev/null @@ -1,313 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.query_vector import QueryVector - from pinecone.core.openapi.db_data.model.sparse_values import SparseValues - - globals()["QueryVector"] = QueryVector - globals()["SparseValues"] = SparseValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="QueryRequest") - - -class QueryRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("top_k",): {"inclusive_maximum": 10000, "inclusive_minimum": 1}, - ("queries",): {}, - ("vector",): {}, - ("id",): {"max_length": 512}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "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: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], top_k, *args, **kwargs) -> T: # 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, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). [optional] # noqa: E501 - include_values (bool): Indicates whether vector values are included in the response. [optional] if omitted the server will use the default value of False. # noqa: E501 - include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. [optional] if omitted the server will use the default value of False. # noqa: E501 - queries ([QueryVector]): DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`. [optional] # noqa: E501 - 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.top_k = top_k - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, top_k, *args, **kwargs) -> None: # 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, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Understanding metadata](https://docs.pinecone.io/guides/data/understanding-metadata). [optional] # noqa: E501 - include_values (bool): Indicates whether vector values are included in the response. [optional] if omitted the server will use the default value of False. # noqa: E501 - include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. [optional] if omitted the server will use the default value of False. # noqa: E501 - queries ([QueryVector]): DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`. [optional] # noqa: E501 - 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.top_k = top_k - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/query_response.py b/pinecone/core/openapi/db_data/model/query_response.py deleted file mode 100644 index fde3a55d3..000000000 --- a/pinecone/core/openapi/db_data/model/query_response.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.scored_vector import ScoredVector - from pinecone.core.openapi.db_data.model.single_query_results import SingleQueryResults - from pinecone.core.openapi.db_data.model.usage import Usage - - globals()["ScoredVector"] = ScoredVector - globals()["SingleQueryResults"] = SingleQueryResults - globals()["Usage"] = Usage - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="QueryResponse") - - -class QueryResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "usage": (Usage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "results": "results", # noqa: E501 - "matches": "matches", # noqa: E501 - "namespace": "namespace", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 - usage (Usage): [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) -> None: # 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 - usage (Usage): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/query_vector.py b/pinecone/core/openapi/db_data/model/query_vector.py deleted file mode 100644 index 30f4c8de8..000000000 --- a/pinecone/core/openapi/db_data/model/query_vector.py +++ /dev/null @@ -1,293 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="QueryVector") - - -class QueryVector(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("values",): {}, - ("top_k",): {"inclusive_maximum": 10000, "inclusive_minimum": 1}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "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: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], values, *args, **kwargs) -> T: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/rpc_status.py b/pinecone/core/openapi/db_data/model/rpc_status.py deleted file mode 100644 index fa824641f..000000000 --- a/pinecone/core/openapi/db_data/model/rpc_status.py +++ /dev/null @@ -1,276 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.protobuf_any import ProtobufAny - - globals()["ProtobufAny"] = ProtobufAny - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="RpcStatus") - - -class RpcStatus(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "code": "code", # noqa: E501 - "message": "message", # noqa: E501 - "details": "details", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/scored_vector.py b/pinecone/core/openapi/db_data/model/scored_vector.py deleted file mode 100644 index 87d51d94d..000000000 --- a/pinecone/core/openapi/db_data/model/scored_vector.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ScoredVector") - - -class ScoredVector(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("id",): {"max_length": 512, "min_length": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "id": "id", # noqa: E501 - "score": "score", # noqa: E501 - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "metadata": "metadata", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], id, *args, **kwargs) -> T: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, id, *args, **kwargs) -> None: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_request.py b/pinecone/core/openapi/db_data/model/search_records_request.py deleted file mode 100644 index 9393c415f..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_request.py +++ /dev/null @@ -1,288 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.search_records_request_query import ( - SearchRecordsRequestQuery, - ) - from pinecone.core.openapi.db_data.model.search_records_request_rerank import ( - SearchRecordsRequestRerank, - ) - - globals()["SearchRecordsRequestQuery"] = SearchRecordsRequestQuery - globals()["SearchRecordsRequestRerank"] = SearchRecordsRequestRerank - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsRequest") - - -class SearchRecordsRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {("fields",): {}} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "query": (SearchRecordsRequestQuery,), # noqa: E501 - "fields": ([str],), # noqa: E501 - "rerank": (SearchRecordsRequestRerank,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "query": "query", # noqa: E501 - "fields": "fields", # noqa: E501 - "rerank": "rerank", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], query, *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsRequest - a model defined in OpenAPI - - Args: - query (SearchRecordsRequestQuery): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - fields ([str]): The fields to return in the search results. [optional] # noqa: E501 - rerank (SearchRecordsRequestRerank): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.query = query - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, query, *args, **kwargs) -> None: # noqa: E501 - """SearchRecordsRequest - a model defined in OpenAPI - - Args: - query (SearchRecordsRequestQuery): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - fields ([str]): The fields to return in the search results. [optional] # noqa: E501 - rerank (SearchRecordsRequestRerank): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.query = query - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_request_query.py b/pinecone/core/openapi/db_data/model/search_records_request_query.py deleted file mode 100644 index 5cedde38e..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_request_query.py +++ /dev/null @@ -1,290 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.search_records_vector import SearchRecordsVector - - globals()["SearchRecordsVector"] = SearchRecordsVector - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsRequestQuery") - - -class SearchRecordsRequestQuery(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {("id",): {"max_length": 512}} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "top_k": (int,), # noqa: E501 - "filter": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "inputs": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "vector": (SearchRecordsVector,), # noqa: E501 - "id": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "top_k": "top_k", # noqa: E501 - "filter": "filter", # noqa: E501 - "inputs": "inputs", # noqa: E501 - "vector": "vector", # noqa: E501 - "id": "id", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], top_k, *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsRequestQuery - a model defined in OpenAPI - - Args: - top_k (int): The number of results to return for each search. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. [optional] # noqa: E501 - inputs ({str: (bool, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - vector (SearchRecordsVector): [optional] # noqa: E501 - id (str): The unique ID of the vector to be used as a query 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.top_k = top_k - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, top_k, *args, **kwargs) -> None: # noqa: E501 - """SearchRecordsRequestQuery - a model defined in OpenAPI - - Args: - top_k (int): The number of results to return for each search. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - filter ({str: (bool, dict, float, int, list, str, none_type)}): The filter to apply. [optional] # noqa: E501 - inputs ({str: (bool, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - vector (SearchRecordsVector): [optional] # noqa: E501 - id (str): The unique ID of the vector to be used as a query 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.top_k = top_k - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_request_rerank.py b/pinecone/core/openapi/db_data/model/search_records_request_rerank.py deleted file mode 100644 index 6b6515bb5..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_request_rerank.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsRequestRerank") - - -class SearchRecordsRequestRerank(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "model": (str,), # noqa: E501 - "rank_fields": ([str],), # noqa: E501 - "top_n": (int,), # noqa: E501 - "parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - "query": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "rank_fields": "rank_fields", # noqa: E501 - "top_n": "top_n", # noqa: E501 - "parameters": "parameters", # noqa: E501 - "query": "query", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, rank_fields, *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsRequestRerank - a model defined in OpenAPI - - Args: - model (str): The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. - rank_fields ([str]): The field(s) to consider for reranking. If not provided, the default is `[\"text\"]`. The number of fields supported is [model-specific](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models). - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - top_n (int): The number of top results to return after reranking. Defaults to top_k. [optional] # noqa: E501 - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters. [optional] # noqa: E501 - query (str): The query to rerank documents against. If a specific rerank query is specified, it overwrites the query input that was provided at the top level. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.rank_fields = rank_fields - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, rank_fields, *args, **kwargs) -> None: # noqa: E501 - """SearchRecordsRequestRerank - a model defined in OpenAPI - - Args: - model (str): The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. - rank_fields ([str]): The field(s) to consider for reranking. If not provided, the default is `[\"text\"]`. The number of fields supported is [model-specific](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models). - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - top_n (int): The number of top results to return after reranking. Defaults to top_k. [optional] # noqa: E501 - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters. [optional] # noqa: E501 - query (str): The query to rerank documents against. If a specific rerank query is specified, it overwrites the query input that was provided at the top level. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.rank_fields = rank_fields - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_response.py b/pinecone/core/openapi/db_data/model/search_records_response.py deleted file mode 100644 index 440fa71b4..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_response.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.search_records_response_result import ( - SearchRecordsResponseResult, - ) - from pinecone.core.openapi.db_data.model.search_usage import SearchUsage - - globals()["SearchRecordsResponseResult"] = SearchRecordsResponseResult - globals()["SearchUsage"] = SearchUsage - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsResponse") - - -class SearchRecordsResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "result": (SearchRecordsResponseResult,), # noqa: E501 - "usage": (SearchUsage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "result": "result", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], result, usage, *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsResponse - a model defined in OpenAPI - - Args: - result (SearchRecordsResponseResult): - usage (SearchUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.result = result - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, result, usage, *args, **kwargs) -> None: # noqa: E501 - """SearchRecordsResponse - a model defined in OpenAPI - - Args: - result (SearchRecordsResponseResult): - usage (SearchUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.result = result - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_response_result.py b/pinecone/core/openapi/db_data/model/search_records_response_result.py deleted file mode 100644 index 87ecf0177..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_response_result.py +++ /dev/null @@ -1,274 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.hit import Hit - - globals()["Hit"] = Hit - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsResponseResult") - - -class SearchRecordsResponseResult(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "hits": ([Hit],) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "hits": "hits" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], hits, *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsResponseResult - a model defined in OpenAPI - - Args: - hits ([Hit]): The hits for the search document request. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.hits = hits - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, hits, *args, **kwargs) -> None: # noqa: E501 - """SearchRecordsResponseResult - a model defined in OpenAPI - - Args: - hits ([Hit]): The hits for the search document request. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.hits = hits - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_records_vector.py b/pinecone/core/openapi/db_data/model/search_records_vector.py deleted file mode 100644 index d2466cd7b..000000000 --- a/pinecone/core/openapi/db_data/model/search_records_vector.py +++ /dev/null @@ -1,276 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.vector_values import VectorValues - - globals()["VectorValues"] = VectorValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchRecordsVector") - - -class SearchRecordsVector(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "values": (VectorValues,), # noqa: E501 - "sparse_values": ([float],), # noqa: E501 - "sparse_indices": ([int],), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "values": "values", # noqa: E501 - "sparse_values": "sparse_values", # noqa: E501 - "sparse_indices": "sparse_indices", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """SearchRecordsVector - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - values (VectorValues): [optional] # noqa: E501 - sparse_values ([float]): The sparse embedding values. [optional] # noqa: E501 - sparse_indices ([int]): The sparse embedding indices. [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) -> None: # noqa: E501 - """SearchRecordsVector - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - values (VectorValues): [optional] # noqa: E501 - sparse_values ([float]): The sparse embedding values. [optional] # noqa: E501 - sparse_indices ([int]): The sparse embedding indices. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_usage.py b/pinecone/core/openapi/db_data/model/search_usage.py deleted file mode 100644 index 565efc9f0..000000000 --- a/pinecone/core/openapi/db_data/model/search_usage.py +++ /dev/null @@ -1,278 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchUsage") - - -class SearchUsage(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("read_units",): {"inclusive_minimum": 0}, - ("embed_total_tokens",): {"inclusive_minimum": 0}, - ("rerank_units",): {"inclusive_minimum": 0}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "read_units": (int,), # noqa: E501 - "embed_total_tokens": (int,), # noqa: E501 - "rerank_units": (int,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "read_units": "read_units", # noqa: E501 - "embed_total_tokens": "embed_total_tokens", # noqa: E501 - "rerank_units": "rerank_units", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], read_units, *args, **kwargs) -> T: # noqa: E501 - """SearchUsage - a model defined in OpenAPI - - Args: - read_units (int): The number of read units consumed by this operation. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - embed_total_tokens (int): The number of embedding tokens consumed by this operation. [optional] # noqa: E501 - rerank_units (int): The number of rerank units consumed by this operation. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.read_units = read_units - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, read_units, *args, **kwargs) -> None: # noqa: E501 - """SearchUsage - a model defined in OpenAPI - - Args: - read_units (int): The number of read units consumed by this operation. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - embed_total_tokens (int): The number of embedding tokens consumed by this operation. [optional] # noqa: E501 - rerank_units (int): The number of rerank units consumed by this operation. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.read_units = read_units - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/search_vector.py b/pinecone/core/openapi/db_data/model/search_vector.py deleted file mode 100644 index 417bde501..000000000 --- a/pinecone/core/openapi/db_data/model/search_vector.py +++ /dev/null @@ -1,268 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.vector_values import VectorValues - - globals()["VectorValues"] = VectorValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SearchVector") - - -class SearchVector(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - "values": (VectorValues,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "values": "values" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """SearchVector - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - values (VectorValues): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs) -> None: # noqa: E501 - """SearchVector - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - values (VectorValues): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/single_query_results.py b/pinecone/core/openapi/db_data/model/single_query_results.py deleted file mode 100644 index b10e442d3..000000000 --- a/pinecone/core/openapi/db_data/model/single_query_results.py +++ /dev/null @@ -1,272 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.scored_vector import ScoredVector - - globals()["ScoredVector"] = ScoredVector - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SingleQueryResults") - - -class SingleQueryResults(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "matches": "matches", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/sparse_values.py b/pinecone/core/openapi/db_data/model/sparse_values.py deleted file mode 100644 index 0883d17e9..000000000 --- a/pinecone/core/openapi/db_data/model/sparse_values.py +++ /dev/null @@ -1,275 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SparseValues") - - -class SparseValues(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("indices",): {}, - ("values",): {}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "indices": "indices", # noqa: E501 - "values": "values", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], indices, values, *args, **kwargs) -> T: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/start_import_request.py b/pinecone/core/openapi/db_data/model/start_import_request.py deleted file mode 100644 index 891de0b26..000000000 --- a/pinecone/core/openapi/db_data/model/start_import_request.py +++ /dev/null @@ -1,285 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.import_error_mode import ImportErrorMode - - globals()["ImportErrorMode"] = ImportErrorMode - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="StartImportRequest") - - -class StartImportRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("uri",): {"max_length": 1500, "min_length": 1}, - ("integration_id",): {"max_length": 1000}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "uri": (str,), # noqa: E501 - "integration_id": (str,), # noqa: E501 - "error_mode": (ImportErrorMode,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "uri": "uri", # noqa: E501 - "integration_id": "integrationId", # noqa: E501 - "error_mode": "errorMode", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], uri, *args, **kwargs) -> T: # noqa: E501 - """StartImportRequest - a model defined in OpenAPI - - Args: - uri (str): The [URI prefix](https://docs.pinecone.io/guides/data/understanding-imports#directory-structure) under which the data to import is available. All data within this prefix will be listed then imported into the target index. Currently only `s3://` URIs are supported. - - 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,) - integration_id (str): The id of the [storage integration](https://docs.pinecone.io/guides/operations/integrations/manage-storage-integrations) that should be used to access the data. [optional] # noqa: E501 - error_mode (ImportErrorMode): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.uri = uri - 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, uri, *args, **kwargs) -> None: # noqa: E501 - """StartImportRequest - a model defined in OpenAPI - - Args: - uri (str): The [URI prefix](https://docs.pinecone.io/guides/data/understanding-imports#directory-structure) under which the data to import is available. All data within this prefix will be listed then imported into the target index. Currently only `s3://` URIs are supported. - - 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,) - integration_id (str): The id of the [storage integration](https://docs.pinecone.io/guides/operations/integrations/manage-storage-integrations) that should be used to access the data. [optional] # noqa: E501 - error_mode (ImportErrorMode): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.uri = uri - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/start_import_response.py b/pinecone/core/openapi/db_data/model/start_import_response.py deleted file mode 100644 index ede992711..000000000 --- a/pinecone/core/openapi/db_data/model/start_import_response.py +++ /dev/null @@ -1,262 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="StartImportResponse") - - -class StartImportResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("id",): {"max_length": 1000, "min_length": 1} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "id": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "id": "id" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """StartImportResponse - 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,) - id (str): Unique identifier for the import 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) -> None: # noqa: E501 - """StartImportResponse - 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,) - id (str): Unique identifier for the import 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/openapi/db_data/model/update_request.py b/pinecone/core/openapi/db_data/model/update_request.py deleted file mode 100644 index cfa9f3442..000000000 --- a/pinecone/core/openapi/db_data/model/update_request.py +++ /dev/null @@ -1,293 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="UpdateRequest") - - -class UpdateRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("id",): {"max_length": 512, "min_length": 1}, - ("values",): {}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - "namespace": (str,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "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: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], id, *args, **kwargs) -> T: # 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, dict, float, int, list, str, none_type)}): Metadata to set for the vector. [optional] # noqa: E501 - namespace (str): The namespace containing the vector to update. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, id, *args, **kwargs) -> None: # 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, dict, float, int, list, str, none_type)}): Metadata to set for the vector. [optional] # noqa: E501 - namespace (str): The namespace containing the vector to update. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/upsert_record.py b/pinecone/core/openapi/db_data/model/upsert_record.py deleted file mode 100644 index b95940ebe..000000000 --- a/pinecone/core/openapi/db_data/model/upsert_record.py +++ /dev/null @@ -1,266 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="UpsertRecord") - - -class UpsertRecord(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "_id": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "_id": "_id" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], _id, *args, **kwargs) -> T: # noqa: E501 - """UpsertRecord - a model defined in OpenAPI - - Args: - _id (str): The unique ID of the record to upsert. Note that `id` can be used as an alias for `_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,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self._id = _id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, _id, *args, **kwargs) -> None: # noqa: E501 - """UpsertRecord - a model defined in OpenAPI - - Args: - _id (str): The unique ID of the record to upsert. Note that `id` can be used as an alias for `_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,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self._id = _id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/upsert_request.py b/pinecone/core/openapi/db_data/model/upsert_request.py deleted file mode 100644 index c842647a0..000000000 --- a/pinecone/core/openapi/db_data/model/upsert_request.py +++ /dev/null @@ -1,278 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.vector import Vector - - globals()["Vector"] = Vector - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="UpsertRequest") - - -class UpsertRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {("vectors",): {}} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "vectors": "vectors", # noqa: E501 - "namespace": "namespace", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], vectors, *args, **kwargs) -> T: # 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): The namespace 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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): The namespace 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/upsert_response.py b/pinecone/core/openapi/db_data/model/upsert_response.py deleted file mode 100644 index 2ba3056de..000000000 --- a/pinecone/core/openapi/db_data/model/upsert_response.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="UpsertResponse") - - -class UpsertResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "upserted_count": "upsertedCount" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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 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) -> None: # 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/usage.py b/pinecone/core/openapi/db_data/model/usage.py deleted file mode 100644 index 7ddc0c28d..000000000 --- a/pinecone/core/openapi/db_data/model/usage.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Usage") - - -class Usage(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "read_units": "readUnits" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # 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) -> None: # 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/openapi/db_data/model/vector.py b/pinecone/core/openapi/db_data/model/vector.py deleted file mode 100644 index 167806f90..000000000 --- a/pinecone/core/openapi/db_data/model/vector.py +++ /dev/null @@ -1,289 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.db_data.model.sparse_values import SparseValues - - globals()["SparseValues"] = SparseValues - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Vector") - - -class Vector(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("id",): {"max_length": 512, "min_length": 1}, - ("values",): {}, - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "id": "id", # noqa: E501 - "values": "values", # noqa: E501 - "sparse_values": "sparseValues", # noqa: E501 - "metadata": "metadata", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], id, *args, **kwargs) -> T: # noqa: E501 - """Vector - 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,) - values ([float]): This is the vector data included in the request. [optional] # noqa: E501 - sparse_values (SparseValues): [optional] # noqa: E501 - metadata ({str: (bool, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, id, *args, **kwargs) -> None: # noqa: E501 - """Vector - 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,) - values ([float]): This is the vector data included in the request. [optional] # noqa: E501 - sparse_values (SparseValues): [optional] # noqa: E501 - metadata ({str: (bool, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.id = id - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/db_data/model/vector_values.py b/pinecone/core/openapi/db_data/model/vector_values.py deleted file mode 100644 index 7777cdc54..000000000 --- a/pinecone/core/openapi/db_data/model/vector_values.py +++ /dev/null @@ -1,282 +0,0 @@ -""" -Pinecone Data Plane API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="VectorValues") - - -class VectorValues(ModelSimple): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {("value",): {}} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return {"value": ([float],)} - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = 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) -> None: - """VectorValues - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([float]): This is the vector data included in the request.. # noqa: E501 - - Keyword Args: - value ([float]): This is the vector data included in the request.. # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: - """VectorValues - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([float]): This is the vector data included in the request. # noqa: E501 - - Keyword Args: - value ([float]): This is the vector data included in the request. # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/openapi/db_data/models/__init__.py b/pinecone/core/openapi/db_data/models/__init__.py deleted file mode 100644 index b5fa9fa0e..000000000 --- a/pinecone/core/openapi/db_data/models/__init__.py +++ /dev/null @@ -1,57 +0,0 @@ -# flake8: noqa - -# 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.openapi.db_data.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.openapi.db_data.model.delete_request import DeleteRequest -from pinecone.core.openapi.db_data.model.describe_index_stats_request import ( - DescribeIndexStatsRequest, -) -from pinecone.core.openapi.db_data.model.fetch_response import FetchResponse -from pinecone.core.openapi.db_data.model.hit import Hit -from pinecone.core.openapi.db_data.model.import_error_mode import ImportErrorMode -from pinecone.core.openapi.db_data.model.import_model import ImportModel -from pinecone.core.openapi.db_data.model.index_description import IndexDescription -from pinecone.core.openapi.db_data.model.list_imports_response import ListImportsResponse -from pinecone.core.openapi.db_data.model.list_item import ListItem -from pinecone.core.openapi.db_data.model.list_response import ListResponse -from pinecone.core.openapi.db_data.model.namespace_summary import NamespaceSummary -from pinecone.core.openapi.db_data.model.pagination import Pagination -from pinecone.core.openapi.db_data.model.protobuf_any import ProtobufAny -from pinecone.core.openapi.db_data.model.protobuf_null_value import ProtobufNullValue -from pinecone.core.openapi.db_data.model.query_request import QueryRequest -from pinecone.core.openapi.db_data.model.query_response import QueryResponse -from pinecone.core.openapi.db_data.model.query_vector import QueryVector -from pinecone.core.openapi.db_data.model.rpc_status import RpcStatus -from pinecone.core.openapi.db_data.model.scored_vector import ScoredVector -from pinecone.core.openapi.db_data.model.search_records_request import SearchRecordsRequest -from pinecone.core.openapi.db_data.model.search_records_request_query import ( - SearchRecordsRequestQuery, -) -from pinecone.core.openapi.db_data.model.search_records_request_rerank import ( - SearchRecordsRequestRerank, -) -from pinecone.core.openapi.db_data.model.search_records_response import SearchRecordsResponse -from pinecone.core.openapi.db_data.model.search_records_response_result import ( - SearchRecordsResponseResult, -) -from pinecone.core.openapi.db_data.model.search_records_vector import SearchRecordsVector -from pinecone.core.openapi.db_data.model.search_usage import SearchUsage -from pinecone.core.openapi.db_data.model.search_vector import SearchVector -from pinecone.core.openapi.db_data.model.single_query_results import SingleQueryResults -from pinecone.core.openapi.db_data.model.sparse_values import SparseValues -from pinecone.core.openapi.db_data.model.start_import_request import StartImportRequest -from pinecone.core.openapi.db_data.model.start_import_response import StartImportResponse -from pinecone.core.openapi.db_data.model.update_request import UpdateRequest -from pinecone.core.openapi.db_data.model.upsert_record import UpsertRecord -from pinecone.core.openapi.db_data.model.upsert_request import UpsertRequest -from pinecone.core.openapi.db_data.model.upsert_response import UpsertResponse -from pinecone.core.openapi.db_data.model.usage import Usage -from pinecone.core.openapi.db_data.model.vector import Vector -from pinecone.core.openapi.db_data.model.vector_values import VectorValues diff --git a/pinecone/core/openapi/inference/__init__.py b/pinecone/core/openapi/inference/__init__.py deleted file mode 100644 index 3e258e4fe..000000000 --- a/pinecone/core/openapi/inference/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# flake8: noqa - -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.openapi_support.api_client import ApiClient - -# import Configuration -from pinecone.openapi_support.configuration import Configuration - -# import exceptions -from pinecone.openapi_support.exceptions import PineconeException -from pinecone.openapi_support.exceptions import PineconeApiAttributeError -from pinecone.openapi_support.exceptions import PineconeApiTypeError -from pinecone.openapi_support.exceptions import PineconeApiValueError -from pinecone.openapi_support.exceptions import PineconeApiKeyError -from pinecone.openapi_support.exceptions import PineconeApiException - -API_VERSION = "2025-01" diff --git a/pinecone/core/openapi/inference/api/__init__.py b/pinecone/core/openapi/inference/api/__init__.py deleted file mode 100644 index 533709993..000000000 --- a/pinecone/core/openapi/inference/api/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# 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.openapi.inference.apis import InferenceApi diff --git a/pinecone/core/openapi/inference/api/inference_api.py b/pinecone/core/openapi/inference/api/inference_api.py deleted file mode 100644 index 1dc0e266d..000000000 --- a/pinecone/core/openapi/inference/api/inference_api.py +++ /dev/null @@ -1,308 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support import ApiClient, AsyncioApiClient -from pinecone.openapi_support.endpoint_utils import ( - ExtraOpenApiKwargsTypedDict, - KwargsWithOpenApiKwargDefaultsTypedDict, -) -from pinecone.openapi_support.endpoint import Endpoint as _Endpoint, ExtraOpenApiKwargsTypedDict -from pinecone.openapi_support.asyncio_endpoint import AsyncioEndpoint as _AsyncioEndpoint -from pinecone.openapi_support.model_utils import ( # noqa: F401 - date, - datetime, - file_type, - none_type, - validate_and_convert_types, -) -from pinecone.core.openapi.inference.model.embed_request import EmbedRequest -from pinecone.core.openapi.inference.model.embeddings_list import EmbeddingsList -from pinecone.core.openapi.inference.model.error_response import ErrorResponse -from pinecone.core.openapi.inference.model.rerank_request import RerankRequest -from pinecone.core.openapi.inference.model.rerank_result import RerankResult - - -class InferenceApi: - """NOTE: This class is @generated using OpenAPI. - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def __embed(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """Embed data # noqa: E501 - - Generate embeddings for input data. For guidance and examples, see [Generate embeddings](https://docs.pinecone.io/guides/inference/generate-embeddings). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.embed(async_req=True) - >>> result = thread.get() - - - Keyword Args: - embed_request (EmbedRequest): Generate embeddings for inputs. [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. - async_req (bool): execute request asynchronously - - Returns: - EmbeddingsList - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - return self.call_with_http_info(**kwargs) - - self.embed = _Endpoint( - settings={ - "response_type": (EmbeddingsList,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/embed", - "operation_id": "embed", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["embed_request"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"embed_request": (EmbedRequest,)}, - "attribute_map": {}, - "location_map": {"embed_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__embed, - ) - - def __rerank(self, **kwargs: ExtraOpenApiKwargsTypedDict): - """Rerank documents # noqa: E501 - - Rerank documents according to their relevance to a query. For guidance and examples, see [Rerank documents](https://docs.pinecone.io/guides/inference/rerank). # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.rerank(async_req=True) - >>> result = thread.get() - - - Keyword Args: - rerank_request (RerankRequest): Rerank documents for the given query [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. - async_req (bool): execute request asynchronously - - Returns: - RerankResult - If the method is called asynchronously, returns the request - thread. - """ - kwargs = self._process_openapi_kwargs(kwargs) - return self.call_with_http_info(**kwargs) - - self.rerank = _Endpoint( - settings={ - "response_type": (RerankResult,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/rerank", - "operation_id": "rerank", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["rerank_request"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"rerank_request": (RerankRequest,)}, - "attribute_map": {}, - "location_map": {"rerank_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__rerank, - ) - - -class AsyncioInferenceApi: - """NOTE: This class is @generated using OpenAPI - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = AsyncioApiClient() - self.api_client = api_client - - async def __embed(self, **kwargs): - """Embed data # noqa: E501 - - Generate embeddings for input data. For guidance and examples, see [Generate embeddings](https://docs.pinecone.io/guides/inference/generate-embeddings). # noqa: E501 - - - - Keyword Args: - embed_request (EmbedRequest): Generate embeddings for inputs. [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. - - Returns: - EmbeddingsList - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.embed = _AsyncioEndpoint( - settings={ - "response_type": (EmbeddingsList,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/embed", - "operation_id": "embed", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["embed_request"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"embed_request": (EmbedRequest,)}, - "attribute_map": {}, - "location_map": {"embed_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__embed, - ) - - async def __rerank(self, **kwargs): - """Rerank documents # noqa: E501 - - Rerank documents according to their relevance to a query. For guidance and examples, see [Rerank documents](https://docs.pinecone.io/guides/inference/rerank). # noqa: E501 - - - - Keyword Args: - rerank_request (RerankRequest): Rerank documents for the given query [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. - - Returns: - RerankResult - """ - self._process_openapi_kwargs(kwargs) - return await self.call_with_http_info(**kwargs) - - self.rerank = _AsyncioEndpoint( - settings={ - "response_type": (RerankResult,), - "auth": ["ApiKeyAuth"], - "endpoint_path": "/rerank", - "operation_id": "rerank", - "http_method": "POST", - "servers": None, - }, - params_map={ - "all": ["rerank_request"], - "required": [], - "nullable": [], - "enum": [], - "validation": [], - }, - root_map={ - "validations": {}, - "allowed_values": {}, - "openapi_types": {"rerank_request": (RerankRequest,)}, - "attribute_map": {}, - "location_map": {"rerank_request": "body"}, - "collection_format_map": {}, - }, - headers_map={"accept": ["application/json"], "content_type": ["application/json"]}, - api_client=api_client, - callable=__rerank, - ) diff --git a/pinecone/core/openapi/inference/apis/__init__.py b/pinecone/core/openapi/inference/apis/__init__.py deleted file mode 100644 index 647ee6f2e..000000000 --- a/pinecone/core/openapi/inference/apis/__init__.py +++ /dev/null @@ -1,16 +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.inference_api import InferenceApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from pinecone.core.openapi.inference.api.inference_api import InferenceApi diff --git a/pinecone/core/openapi/inference/model/__init__.py b/pinecone/core/openapi/inference/model/__init__.py deleted file mode 100644 index cfe32b784..000000000 --- a/pinecone/core/openapi/inference/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/openapi/inference/model/dense_embedding.py b/pinecone/core/openapi/inference/model/dense_embedding.py deleted file mode 100644 index fe841f99c..000000000 --- a/pinecone/core/openapi/inference/model/dense_embedding.py +++ /dev/null @@ -1,280 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.vector_type import VectorType - - globals()["VectorType"] = VectorType - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="DenseEmbedding") - - -class DenseEmbedding(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 - "vector_type": (VectorType,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "values": "values", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], values, vector_type, *args, **kwargs) -> T: # noqa: E501 - """DenseEmbedding - a model defined in OpenAPI - - Args: - values ([float]): The dense embedding values. - vector_type (VectorType): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.values = values - self.vector_type = vector_type - 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, vector_type, *args, **kwargs) -> None: # noqa: E501 - """DenseEmbedding - a model defined in OpenAPI - - Args: - values ([float]): The dense embedding values. - vector_type (VectorType): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.values = values - self.vector_type = vector_type - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/document.py b/pinecone/core/openapi/inference/model/document.py deleted file mode 100644 index 159969aa3..000000000 --- a/pinecone/core/openapi/inference/model/document.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Document") - - -class Document(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 {} - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """Document - 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,) - """ - - _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) -> None: # noqa: E501 - """Document - 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,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/embed_request.py b/pinecone/core/openapi/inference/model/embed_request.py deleted file mode 100644 index 6f91a05a6..000000000 --- a/pinecone/core/openapi/inference/model/embed_request.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.embed_request_inputs import EmbedRequestInputs - - globals()["EmbedRequestInputs"] = EmbedRequestInputs - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="EmbedRequest") - - -class EmbedRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "model": (str,), # noqa: E501 - "inputs": ([EmbedRequestInputs],), # noqa: E501 - "parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "inputs": "inputs", # noqa: E501 - "parameters": "parameters", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, inputs, *args, **kwargs) -> T: # noqa: E501 - """EmbedRequest - a model defined in OpenAPI - - Args: - model (str): The [model](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) to use for embedding generation. - inputs ([EmbedRequestInputs]): List of inputs to generate embeddings for. - - 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,) - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) for available model parameters. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.inputs = inputs - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, inputs, *args, **kwargs) -> None: # noqa: E501 - """EmbedRequest - a model defined in OpenAPI - - Args: - model (str): The [model](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) to use for embedding generation. - inputs ([EmbedRequestInputs]): List of inputs to generate embeddings for. - - 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,) - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#embedding-models) for available model parameters. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.inputs = inputs - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/embed_request_inputs.py b/pinecone/core/openapi/inference/model/embed_request_inputs.py deleted file mode 100644 index 44832a2e0..000000000 --- a/pinecone/core/openapi/inference/model/embed_request_inputs.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="EmbedRequestInputs") - - -class EmbedRequestInputs(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "text": (str,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "text": "text" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """EmbedRequestInputs - 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,) - text (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 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) -> None: # noqa: E501 - """EmbedRequestInputs - 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,) - text (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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/embedding.py b/pinecone/core/openapi/inference/model/embedding.py deleted file mode 100644 index a7150a27c..000000000 --- a/pinecone/core/openapi/inference/model/embedding.py +++ /dev/null @@ -1,337 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.dense_embedding import DenseEmbedding - from pinecone.core.openapi.inference.model.sparse_embedding import SparseEmbedding - from pinecone.core.openapi.inference.model.vector_type import VectorType - - globals()["DenseEmbedding"] = DenseEmbedding - globals()["SparseEmbedding"] = SparseEmbedding - globals()["VectorType"] = VectorType - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="Embedding") - - -class Embedding(ModelComposed): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "vector_type": (VectorType,), # noqa: E501 - "sparse_tokens": ([str],), # noqa: E501 - "values": ([float],), # noqa: E501 - "sparse_values": ([float],), # noqa: E501 - "sparse_indices": ([int],), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - lazy_import() - val = { - "DenseEmbedding": DenseEmbedding, - "SparseEmbedding": SparseEmbedding, - "dense": DenseEmbedding, - "sparse": SparseEmbedding, - } - if not val: - return None - return {"vector_type": val} - - attribute_map: Dict[str, str] = { - "vector_type": "vector_type", # noqa: E501 - "sparse_tokens": "sparse_tokens", # noqa: E501 - "values": "values", # noqa: E501 - "sparse_values": "sparse_values", # noqa: E501 - "sparse_indices": "sparse_indices", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """Embedding - a model defined in OpenAPI - - Keyword Args: - vector_type (VectorType): - _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_tokens ([str]): The normalized tokens used to create the sparse embedding. [optional] # noqa: E501 - values ([float]): The dense embedding values. [optional] # noqa: E501 - sparse_values ([float]): The sparse embedding values. [optional] # noqa: E501 - sparse_indices ([int]): The sparse embedding indices. [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__,) - - constant_args = { - "_check_type": _check_type, - "_path_to_item": _path_to_item, - "_spec_property_naming": _spec_property_naming, - "_configuration": _configuration, - "_visited_composed_classes": self._visited_composed_classes, - } - composed_info = validate_get_composed_info(constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if ( - var_name in discarded_args - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self._additional_properties_model_instances - ): - # 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", - "_composed_instances", - "_var_name_to_model_instances", - "_additional_properties_model_instances", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs) -> None: # noqa: E501 - """Embedding - a model defined in OpenAPI - - Keyword Args: - vector_type (VectorType): - _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_tokens ([str]): The normalized tokens used to create the sparse embedding. [optional] # noqa: E501 - values ([float]): The dense embedding values. [optional] # noqa: E501 - sparse_values ([float]): The sparse embedding values. [optional] # noqa: E501 - sparse_indices ([int]): The sparse embedding indices. [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__,) - - constant_args = { - "_check_type": _check_type, - "_path_to_item": _path_to_item, - "_spec_property_naming": _spec_property_naming, - "_configuration": _configuration, - "_visited_composed_classes": self._visited_composed_classes, - } - composed_info = validate_get_composed_info(constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if ( - var_name in discarded_args - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self._additional_properties_model_instances - ): - # 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." - ) - - @cached_property - def _composed_schemas(): # type: ignore - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error beause the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return {"anyOf": [], "allOf": [], "oneOf": [DenseEmbedding, SparseEmbedding]} diff --git a/pinecone/core/openapi/inference/model/embeddings_list.py b/pinecone/core/openapi/inference/model/embeddings_list.py deleted file mode 100644 index 0b7de1ef5..000000000 --- a/pinecone/core/openapi/inference/model/embeddings_list.py +++ /dev/null @@ -1,294 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.embedding import Embedding - from pinecone.core.openapi.inference.model.embeddings_list_usage import EmbeddingsListUsage - - globals()["Embedding"] = Embedding - globals()["EmbeddingsListUsage"] = EmbeddingsListUsage - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="EmbeddingsList") - - -class EmbeddingsList(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "model": (str,), # noqa: E501 - "vector_type": (str,), # noqa: E501 - "data": ([Embedding],), # noqa: E501 - "usage": (EmbeddingsListUsage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - "data": "data", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, vector_type, data, usage, *args, **kwargs) -> T: # noqa: E501 - """EmbeddingsList - a model defined in OpenAPI - - Args: - model (str): The model used to generate the embeddings - vector_type (str): Indicates whether the response data contains 'dense' or 'sparse' embeddings. - data ([Embedding]): The embeddings generated for the inputs. - usage (EmbeddingsListUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.vector_type = vector_type - self.data = data - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, vector_type, data, usage, *args, **kwargs) -> None: # noqa: E501 - """EmbeddingsList - a model defined in OpenAPI - - Args: - model (str): The model used to generate the embeddings - vector_type (str): Indicates whether the response data contains 'dense' or 'sparse' embeddings. - data ([Embedding]): The embeddings generated for the inputs. - usage (EmbeddingsListUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.vector_type = vector_type - self.data = data - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/embeddings_list_usage.py b/pinecone/core/openapi/inference/model/embeddings_list_usage.py deleted file mode 100644 index 95e3263e6..000000000 --- a/pinecone/core/openapi/inference/model/embeddings_list_usage.py +++ /dev/null @@ -1,262 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="EmbeddingsListUsage") - - -class EmbeddingsListUsage(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("total_tokens",): {"inclusive_minimum": 0} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "total_tokens": (int,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "total_tokens": "total_tokens" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """EmbeddingsListUsage - 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,) - total_tokens (int): Total number of tokens consumed across all inputs. [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) -> None: # noqa: E501 - """EmbeddingsListUsage - 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,) - total_tokens (int): Total number of tokens consumed across all inputs. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/error_response.py b/pinecone/core/openapi/inference/model/error_response.py deleted file mode 100644 index ce18d3628..000000000 --- a/pinecone/core/openapi/inference/model/error_response.py +++ /dev/null @@ -1,280 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.error_response_error import ErrorResponseError - - globals()["ErrorResponseError"] = ErrorResponseError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ErrorResponse") - - -class ErrorResponse(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "status": (int,), # noqa: E501 - "error": (ErrorResponseError,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "status": "status", # noqa: E501 - "error": "error", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], status, error, *args, **kwargs) -> T: # noqa: E501 - """ErrorResponse - a model defined in OpenAPI - - Args: - status (int): The HTTP status code of the error. - error (ErrorResponseError): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 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, status, error, *args, **kwargs) -> None: # noqa: E501 - """ErrorResponse - a model defined in OpenAPI - - Args: - status (int): The HTTP status code of the error. - error (ErrorResponseError): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/error_response_error.py b/pinecone/core/openapi/inference/model/error_response_error.py deleted file mode 100644 index e68848256..000000000 --- a/pinecone/core/openapi/inference/model/error_response_error.py +++ /dev/null @@ -1,297 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="ErrorResponseError") - - -class ErrorResponseError(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("code",): { - "OK": "OK", - "UNKNOWN": "UNKNOWN", - "INVALID_ARGUMENT": "INVALID_ARGUMENT", - "DEADLINE_EXCEEDED": "DEADLINE_EXCEEDED", - "QUOTA_EXCEEDED": "QUOTA_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", - "FORBIDDEN": "FORBIDDEN", - } - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "code": "code", # noqa: E501 - "message": "message", # noqa: E501 - "details": "details", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], code, message, *args, **kwargs) -> T: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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) -> None: # 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, 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 PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.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 PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/ranked_document.py b/pinecone/core/openapi/inference/model/ranked_document.py deleted file mode 100644 index 6223c752b..000000000 --- a/pinecone/core/openapi/inference/model/ranked_document.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.document import Document - - globals()["Document"] = Document - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="RankedDocument") - - -class RankedDocument(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "index": (int,), # noqa: E501 - "score": (float,), # noqa: E501 - "document": (Document,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "index": "index", # noqa: E501 - "score": "score", # noqa: E501 - "document": "document", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], index, score, *args, **kwargs) -> T: # noqa: E501 - """RankedDocument - a model defined in OpenAPI - - Args: - index (int): The index position of the document from the original request. - score (float): The relevance of the document to the query, normalized between 0 and 1, with scores closer to 1 indicating higher relevance. - - 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,) - document (Document): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.index = index - self.score = score - 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, index, score, *args, **kwargs) -> None: # noqa: E501 - """RankedDocument - a model defined in OpenAPI - - Args: - index (int): The index position of the document from the original request. - score (float): The relevance of the document to the query, normalized between 0 and 1, with scores closer to 1 indicating higher relevance. - - 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,) - document (Document): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.index = index - self.score = score - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/rerank_request.py b/pinecone/core/openapi/inference/model/rerank_request.py deleted file mode 100644 index dea9ee3c9..000000000 --- a/pinecone/core/openapi/inference/model/rerank_request.py +++ /dev/null @@ -1,302 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.document import Document - - globals()["Document"] = Document - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="RerankRequest") - - -class RerankRequest(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "model": (str,), # noqa: E501 - "query": (str,), # noqa: E501 - "documents": ([Document],), # noqa: E501 - "top_n": (int,), # noqa: E501 - "return_documents": (bool,), # noqa: E501 - "rank_fields": ([str],), # noqa: E501 - "parameters": ({str: (bool, dict, float, int, list, str, none_type)},), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "query": "query", # noqa: E501 - "documents": "documents", # noqa: E501 - "top_n": "top_n", # noqa: E501 - "return_documents": "return_documents", # noqa: E501 - "rank_fields": "rank_fields", # noqa: E501 - "parameters": "parameters", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, query, documents, *args, **kwargs) -> T: # noqa: E501 - """RerankRequest - a model defined in OpenAPI - - Args: - model (str): The [model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use for reranking. - query (str): The query to rerank documents against. - documents ([Document]): The documents to rerank. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - top_n (int): The number of results to return sorted by relevance. Defaults to the number of inputs. [optional] # noqa: E501 - return_documents (bool): Whether to return the documents in the response. [optional] if omitted the server will use the default value of True. # noqa: E501 - rank_fields ([str]): The field(s) to consider for reranking. If not provided, the default is `[\"text\"]`. The number of fields supported is [model-specific](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models). [optional] if omitted the server will use the default value of ["text"]. # noqa: E501 - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.query = query - self.documents = documents - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, query, documents, *args, **kwargs) -> None: # noqa: E501 - """RerankRequest - a model defined in OpenAPI - - Args: - model (str): The [model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use for reranking. - query (str): The query to rerank documents against. - documents ([Document]): The documents to rerank. - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - top_n (int): The number of results to return sorted by relevance. Defaults to the number of inputs. [optional] # noqa: E501 - return_documents (bool): Whether to return the documents in the response. [optional] if omitted the server will use the default value of True. # noqa: E501 - rank_fields ([str]): The field(s) to consider for reranking. If not provided, the default is `[\"text\"]`. The number of fields supported is [model-specific](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models). [optional] if omitted the server will use the default value of ["text"]. # noqa: E501 - parameters ({str: (bool, dict, float, int, list, str, none_type)}): Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) for available model parameters. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.query = query - self.documents = documents - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/rerank_result.py b/pinecone/core/openapi/inference/model/rerank_result.py deleted file mode 100644 index 2abeb4825..000000000 --- a/pinecone/core/openapi/inference/model/rerank_result.py +++ /dev/null @@ -1,288 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.ranked_document import RankedDocument - from pinecone.core.openapi.inference.model.rerank_result_usage import RerankResultUsage - - globals()["RankedDocument"] = RankedDocument - globals()["RerankResultUsage"] = RerankResultUsage - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="RerankResult") - - -class RerankResult(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "model": (str,), # noqa: E501 - "data": ([RankedDocument],), # noqa: E501 - "usage": (RerankResultUsage,), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "model": "model", # noqa: E501 - "data": "data", # noqa: E501 - "usage": "usage", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], model, data, usage, *args, **kwargs) -> T: # noqa: E501 - """RerankResult - a model defined in OpenAPI - - Args: - model (str): The model used to rerank documents. - data ([RankedDocument]): The reranked documents. - usage (RerankResultUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.data = data - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, model, data, usage, *args, **kwargs) -> None: # noqa: E501 - """RerankResult - a model defined in OpenAPI - - Args: - model (str): The model used to rerank documents. - data ([RankedDocument]): The reranked documents. - usage (RerankResultUsage): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.model = model - self.data = data - self.usage = usage - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/rerank_result_usage.py b/pinecone/core/openapi/inference/model/rerank_result_usage.py deleted file mode 100644 index 44f45c33f..000000000 --- a/pinecone/core/openapi/inference/model/rerank_result_usage.py +++ /dev/null @@ -1,262 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="RerankResultUsage") - - -class RerankResultUsage(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = { - ("rerank_units",): {"inclusive_minimum": 0} - } - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "rerank_units": (int,) # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "rerank_units": "rerank_units" # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: # noqa: E501 - """RerankResultUsage - 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,) - rerank_units (int): The number of rerank units consumed by this operation. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - 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) -> None: # noqa: E501 - """RerankResultUsage - 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,) - rerank_units (int): The number of rerank units consumed by this operation. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/sparse_embedding.py b/pinecone/core/openapi/inference/model/sparse_embedding.py deleted file mode 100644 index f4f974150..000000000 --- a/pinecone/core/openapi/inference/model/sparse_embedding.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -def lazy_import(): - from pinecone.core.openapi.inference.model.vector_type import VectorType - - globals()["VectorType"] = VectorType - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="SparseEmbedding") - - -class SparseEmbedding(ModelNormal): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = {} - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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 { - "sparse_values": ([float],), # noqa: E501 - "sparse_indices": ([int],), # noqa: E501 - "vector_type": (VectorType,), # noqa: E501 - "sparse_tokens": ([str],), # noqa: E501 - } - - @cached_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = { - "sparse_values": "sparse_values", # noqa: E501 - "sparse_indices": "sparse_indices", # noqa: E501 - "vector_type": "vector_type", # noqa: E501 - "sparse_tokens": "sparse_tokens", # noqa: E501 - } - - read_only_vars: Set[str] = set([]) - - _composed_schemas: Dict[Literal["allOf", "oneOf", "anyOf"], Any] = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data( - cls: Type[T], sparse_values, sparse_indices, vector_type, *args, **kwargs - ) -> T: # noqa: E501 - """SparseEmbedding - a model defined in OpenAPI - - Args: - sparse_values ([float]): The sparse embedding values. - sparse_indices ([int]): The sparse embedding indices. - vector_type (VectorType): - - 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_tokens ([str]): The normalized tokens used to create the sparse embedding. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.sparse_values = sparse_values - self.sparse_indices = sparse_indices - self.vector_type = vector_type - 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, sparse_values, sparse_indices, vector_type, *args, **kwargs) -> None: # noqa: E501 - """SparseEmbedding - a model defined in OpenAPI - - Args: - sparse_values ([float]): The sparse embedding values. - sparse_indices ([int]): The sparse embedding indices. - vector_type (VectorType): - - 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_tokens ([str]): The normalized tokens used to create the sparse embedding. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _path_to_item = kwargs.pop("_path_to_item", ()) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % (args, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.sparse_values = sparse_values - self.sparse_indices = sparse_indices - self.vector_type = vector_type - for var_name, var_value in kwargs.items(): - if ( - var_name not in self.attribute_map - and self._configuration is not None - and self._configuration.discard_unknown_keys - and self.additional_properties_type is None - ): - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise PineconeApiAttributeError( - f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes." - ) diff --git a/pinecone/core/openapi/inference/model/vector_type.py b/pinecone/core/openapi/inference/model/vector_type.py deleted file mode 100644 index ffeb8706d..000000000 --- a/pinecone/core/openapi/inference/model/vector_type.py +++ /dev/null @@ -1,284 +0,0 @@ -""" -Pinecone Inference API - -Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - -This file is @generated using OpenAPI. - -The version of the OpenAPI document: 2025-01 -Contact: support@pinecone.io -""" - -from pinecone.openapi_support.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - OpenApiModel, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from pinecone.openapi_support.exceptions import PineconeApiAttributeError - - -from typing import Dict, Literal, Tuple, Set, Any, Type, TypeVar -from pinecone.openapi_support import PropertyValidationTypedDict, cached_class_property - -T = TypeVar("T", bound="VectorType") - - -class VectorType(ModelSimple): - """NOTE: This class is @generated using OpenAPI. - - 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. - """ - - _data_store: Dict[str, Any] - _check_type: bool - - allowed_values: Dict[Tuple[str, ...], Dict[str, Any]] = { - ("value",): {"DENSE": "dense", "SPARSE": "sparse"} - } - - validations: Dict[Tuple[str, ...], PropertyValidationTypedDict] = {} - - @cached_class_property - def additional_properties_type(cls): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, dict, float, int, list, str, none_type) # noqa: E501 - - _nullable = False - - @cached_class_property - def openapi_types(cls): - """ - 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_class_property - def discriminator(cls): - return None - - attribute_map: Dict[str, str] = {} - - read_only_vars: Set[str] = 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) -> None: - """VectorType - 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): Indicates whether this is a 'dense' or 'sparse' embedding.., must be one of ["dense", "sparse", ] # noqa: E501 - - Keyword Args: - value (str): Indicates whether this is a 'dense' or 'sparse' embedding.., must be one of ["dense", "sparse", ] # 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", ()) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls: Type[T], *args, **kwargs) -> T: - """VectorType - 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): Indicates whether this is a 'dense' or 'sparse' embedding., must be one of ["dense", "sparse", ] # noqa: E501 - - Keyword Args: - value (str): Indicates whether this is a 'dense' or 'sparse' embedding., must be one of ["dense", "sparse", ] # 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) - - value = None - if "value" in kwargs: - value = kwargs.pop("value") - - if value is None and args: - if len(args) == 1: - value = args[0] - elif len(args) > 1: - 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__,), - ) - - if value is None: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % (kwargs, self.__class__.__name__), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/openapi/inference/models/__init__.py b/pinecone/core/openapi/inference/models/__init__.py deleted file mode 100644 index bbb2cd34d..000000000 --- a/pinecone/core/openapi/inference/models/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -# flake8: noqa - -# 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.openapi.inference.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.openapi.inference.model.dense_embedding import DenseEmbedding -from pinecone.core.openapi.inference.model.document import Document -from pinecone.core.openapi.inference.model.embed_request import EmbedRequest -from pinecone.core.openapi.inference.model.embed_request_inputs import EmbedRequestInputs -from pinecone.core.openapi.inference.model.embedding import Embedding -from pinecone.core.openapi.inference.model.embeddings_list import EmbeddingsList -from pinecone.core.openapi.inference.model.embeddings_list_usage import EmbeddingsListUsage -from pinecone.core.openapi.inference.model.error_response import ErrorResponse -from pinecone.core.openapi.inference.model.error_response_error import ErrorResponseError -from pinecone.core.openapi.inference.model.ranked_document import RankedDocument -from pinecone.core.openapi.inference.model.rerank_request import RerankRequest -from pinecone.core.openapi.inference.model.rerank_result import RerankResult -from pinecone.core.openapi.inference.model.rerank_result_usage import RerankResultUsage -from pinecone.core.openapi.inference.model.sparse_embedding import SparseEmbedding -from pinecone.core.openapi.inference.model.vector_type import VectorType diff --git a/pinecone/data/__init__.py b/pinecone/data/__init__.py deleted file mode 100644 index 8e0400562..000000000 --- a/pinecone/data/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -from .index import ( - Index as _Index, - FetchResponse, - QueryResponse, - DescribeIndexStatsResponse, - UpsertResponse, - SparseValues, - Vector, -) -from .dataclasses import * -from .import_error import ( - Index, - IndexClientInstantiationError, - Inference, - InferenceInstantiationError, -) -from .index_asyncio import * -from .errors import ( - VectorDictionaryMissingKeysError, - VectorDictionaryExcessKeysError, - VectorTupleLengthError, - SparseValuesTypeError, - SparseValuesMissingKeysError, - SparseValuesDictionaryExpectedError, - MetadataDictionaryExpectedError, -) - -from .features.bulk_import import ImportErrorMode -from .features.inference import ( - Inference as _Inference, - AsyncioInference as _AsyncioInference, - RerankModel, - EmbedModel, -) diff --git a/pinecone/data/dataclasses/__init__.py b/pinecone/data/dataclasses/__init__.py deleted file mode 100644 index 0183eb74e..000000000 --- a/pinecone/data/dataclasses/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .sparse_values import SparseValues -from .vector import Vector -from .fetch_response import FetchResponse -from .search_query import SearchQuery -from .search_query_vector import SearchQueryVector -from .search_rerank import SearchRerank diff --git a/pinecone/data/dataclasses/fetch_response.py b/pinecone/data/dataclasses/fetch_response.py deleted file mode 100644 index e8d280695..000000000 --- a/pinecone/data/dataclasses/fetch_response.py +++ /dev/null @@ -1,11 +0,0 @@ -from dataclasses import dataclass -from typing import Dict - -from .vector import Vector - - -@dataclass -class FetchResponse: - namespace: str - vectors: Dict[str, Vector] - usage: Dict[str, int] diff --git a/pinecone/data/dataclasses/search_query.py b/pinecone/data/dataclasses/search_query.py deleted file mode 100644 index 3adb80829..000000000 --- a/pinecone/data/dataclasses/search_query.py +++ /dev/null @@ -1,59 +0,0 @@ -from dataclasses import dataclass -from typing import Optional, Any, Dict, Union -from .search_query_vector import SearchQueryVector -from ..types.search_query_vector_typed_dict import SearchQueryVectorTypedDict - - -@dataclass -class SearchQuery: - """ - SearchQuery represents the query when searching within a specific namespace. - """ - - inputs: Dict[str, Any] - """ - The input data to search with. - Required. - """ - - top_k: int - """ - The number of results to return with each search. - Required. - """ - - filter: Optional[Dict[str, Any]] = None - """ - The filter to apply to the search. - Optional. - """ - - vector: Optional[Union[SearchQueryVectorTypedDict, SearchQueryVector]] = None - """ - The vector values to search with. If provided, it overwrites the inputs. - """ - - id: Optional[str] = None - """ - The unique ID of the vector to be used as a query vector. - """ - - def __post_init__(self): - """ - Converts `vector` to a `SearchQueryVectorTypedDict` instance if an enum is provided. - """ - if isinstance(self.vector, SearchQueryVector): - self.vector = self.vector.as_dict() - - def as_dict(self) -> Dict[str, Any]: - """ - Returns the SearchQuery as a dictionary. - """ - d = { - "inputs": self.inputs, - "top_k": self.top_k, - "filter": self.filter, - "vector": self.vector, - "id": self.id, - } - return {k: v for k, v in d.items() if v is not None} diff --git a/pinecone/data/dataclasses/search_query_vector.py b/pinecone/data/dataclasses/search_query_vector.py deleted file mode 100644 index d829102f6..000000000 --- a/pinecone/data/dataclasses/search_query_vector.py +++ /dev/null @@ -1,38 +0,0 @@ -from dataclasses import dataclass -from typing import Optional, List - - -@dataclass -class SearchQueryVector: - """ - SearchQueryVector represents the vector values used to query. - """ - - values: Optional[List[float]] = None - """ - The vector data included in the search request. - Optional. - """ - - sparse_values: Optional[List[float]] = None - """ - The sparse embedding values to search with. - Optional. - """ - - sparse_indices: Optional[List[int]] = None - """ - The sparse embedding indices to search with. - Optional. - """ - - def as_dict(self) -> dict: - """ - Returns the SearchQueryVector as a dictionary. - """ - d = { - "values": self.values, - "sparse_values": self.sparse_values, - "sparse_indices": self.sparse_indices, - } - return {k: v for k, v in d.items() if v is not None} diff --git a/pinecone/data/dataclasses/search_rerank.py b/pinecone/data/dataclasses/search_rerank.py deleted file mode 100644 index 1b9534ba3..000000000 --- a/pinecone/data/dataclasses/search_rerank.py +++ /dev/null @@ -1,61 +0,0 @@ -from dataclasses import dataclass -from typing import Optional, Dict, Any, List -from ..features.inference import RerankModel - - -@dataclass -class SearchRerank: - """ - SearchRerank represents a rerank request when searching within a specific namespace. - """ - - model: str - """ - The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. - Required. - """ - - rank_fields: List[str] - """ - The fields to use for reranking. - Required. - """ - - top_n: Optional[int] = None - """ - The number of top results to return after reranking. Defaults to top_k. - Optional. - """ - - parameters: Optional[Dict[str, Any]] = None - """ - Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#models) - for available model parameters. - Optional. - """ - - query: Optional[str] = None - """ - The query to rerank documents against. If a specific rerank query is specified, it overwrites - the query input that was provided at the top level. - """ - - def __post_init__(self): - """ - Converts `model` to a string if an instance of `RerankEnum` is provided. - """ - if isinstance(self.model, RerankModel): - self.model = self.model.value # Convert Enum to string - - def as_dict(self) -> Dict[str, Any]: - """ - Returns the SearchRerank as a dictionary. - """ - d = { - "model": self.model, - "rank_fields": self.rank_fields, - "top_n": self.top_n, - "parameters": self.parameters, - "query": self.query, - } - return {k: v for k, v in d.items() if v is not None} diff --git a/pinecone/data/dataclasses/sparse_values.py b/pinecone/data/dataclasses/sparse_values.py deleted file mode 100644 index 536d365e5..000000000 --- a/pinecone/data/dataclasses/sparse_values.py +++ /dev/null @@ -1,20 +0,0 @@ -from dataclasses import dataclass - -from typing import List -from .utils import DictLike -from ..types import SparseVectorTypedDict - - -@dataclass -class SparseValues(DictLike): - indices: List[int] - values: List[float] - - def to_dict(self) -> SparseVectorTypedDict: - return {"indices": self.indices, "values": self.values} - - @staticmethod - def from_dict(sparse_values_dict: SparseVectorTypedDict) -> "SparseValues": - return SparseValues( - indices=sparse_values_dict["indices"], values=sparse_values_dict["values"] - ) diff --git a/pinecone/data/dataclasses/utils.py b/pinecone/data/dataclasses/utils.py deleted file mode 100644 index 29c8e4e4f..000000000 --- a/pinecone/data/dataclasses/utils.py +++ /dev/null @@ -1,11 +0,0 @@ -class DictLike: - def __getitem__(self, key): - if key in self.__dataclass_fields__: - return getattr(self, key) - raise KeyError(f"{key} is not a valid field") - - def __setitem__(self, key, value): - if key in self.__dataclass_fields__: - setattr(self, key, value) - else: - raise KeyError(f"{key} is not a valid field") diff --git a/pinecone/data/dataclasses/vector.py b/pinecone/data/dataclasses/vector.py deleted file mode 100644 index ef280189b..000000000 --- a/pinecone/data/dataclasses/vector.py +++ /dev/null @@ -1,41 +0,0 @@ -from typing import List, Optional -from .sparse_values import SparseValues -from .utils import DictLike -from ..types import VectorTypedDict, VectorMetadataTypedDict - -from dataclasses import dataclass, field - - -@dataclass -class Vector(DictLike): - id: str - values: List[float] = field(default_factory=list) - metadata: Optional[VectorMetadataTypedDict] = None - sparse_values: Optional[SparseValues] = None - - def __post_init__(self): - if self.sparse_values is None and len(self.values) == 0: - raise ValueError("The values and sparse_values fields cannot both be empty") - - def to_dict(self) -> VectorTypedDict: - vector_dict: VectorTypedDict = {"id": self.id, "values": self.values} - if self.metadata is not None: - vector_dict["metadata"] = self.metadata - if self.sparse_values is not None: - vector_dict["sparse_values"] = self.sparse_values.to_dict() - return vector_dict - - @staticmethod - def from_dict(vector_dict: VectorTypedDict) -> "Vector": - passed_sparse_values = vector_dict.get("sparse_values") - if passed_sparse_values is not None: - parsed_sparse_values = SparseValues.from_dict(passed_sparse_values) - else: - parsed_sparse_values = None - - return Vector( - id=vector_dict["id"], - values=vector_dict["values"], - metadata=vector_dict.get("metadata"), - sparse_values=parsed_sparse_values, - ) diff --git a/pinecone/data/errors.py b/pinecone/data/errors.py deleted file mode 100644 index e375d9d5c..000000000 --- a/pinecone/data/errors.py +++ /dev/null @@ -1,46 +0,0 @@ -from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS - - -class VectorDictionaryMissingKeysError(ValueError): - def __init__(self, item) -> None: - 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) -> None: - 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) -> None: - 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, TypeError): - def __init__(self) -> None: - 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) -> None: - 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, TypeError): - def __init__(self, sparse_values_dict) -> None: - message = f"Column `sparse_values` is expected to be a dictionary, found {type(sparse_values_dict)}" - super().__init__(message) - - -class MetadataDictionaryExpectedError(ValueError, TypeError): - def __init__(self, item) -> None: - message = ( - f"Column `metadata` is expected to be a dictionary, found {type(item['metadata'])}" - ) - super().__init__(message) diff --git a/pinecone/data/features/__init__.py b/pinecone/data/features/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/data/features/bulk_import/__init__.py b/pinecone/data/features/bulk_import/__init__.py deleted file mode 100644 index ebcf782b2..000000000 --- a/pinecone/data/features/bulk_import/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .bulk_import_request_factory import ImportErrorMode -from .bulk_import import ImportFeatureMixin -from .bulk_import_asyncio import ImportFeatureMixinAsyncio diff --git a/pinecone/data/features/bulk_import/bulk_import.py b/pinecone/data/features/bulk_import/bulk_import.py deleted file mode 100644 index fdad3aa98..000000000 --- a/pinecone/data/features/bulk_import/bulk_import.py +++ /dev/null @@ -1,152 +0,0 @@ -from typing import Optional, Literal, Iterator, List, Union - -from pinecone.core.openapi.db_data.api.bulk_operations_api import BulkOperationsApi - -from pinecone.utils import install_json_repr_override - -from pinecone.core.openapi.db_data.models import ( - StartImportResponse, - ListImportsResponse, - ImportModel, -) - -from .bulk_import_request_factory import BulkImportRequestFactory, ImportErrorMode - -for m in [StartImportResponse, ListImportsResponse, ImportModel]: - install_json_repr_override(m) - - -class ImportFeatureMixin: - def __init__(self, api_client, **kwargs) -> None: - self.__import_operations_api = BulkOperationsApi(api_client) - - def start_import( - self, - uri: str, - integration_id: Optional[str] = None, - error_mode: Optional[ - Union[ImportErrorMode, Literal["CONTINUE", "ABORT"], str] - ] = "CONTINUE", - ) -> StartImportResponse: - """ - Args: - uri (str): The URI of the data to import. The URI must start with the scheme of a supported storage provider. - integration_id (Optional[str], optional): If your bucket requires authentication to access, you need to pass the id of your storage integration using this property. Defaults to None. - error_mode: Defaults to "CONTINUE". If set to "CONTINUE", the import operation will continue even if some - records fail to import. Pass "ABORT" to stop the import operation if any records fail to import. - - Returns: - `StartImportResponse`: Contains the id of the import operation. - - Import data from a storage provider into an index. The uri must start with the scheme of a supported - storage provider. For buckets that are not publicly readable, you will also need to separately configure - a storage integration and pass the integration id. - - Examples: - >>> from pinecone import Pinecone - >>> index = Pinecone().Index('my-index') - >>> index.start_import(uri="s3://bucket-name/path/to/data.parquet") - { id: "1" } - """ - req = BulkImportRequestFactory.start_import_request( - uri=uri, integration_id=integration_id, error_mode=error_mode - ) - return self.__import_operations_api.start_bulk_import(req) - - def list_imports(self, **kwargs) -> Iterator[List[ImportModel]]: - """ - Args: - limit (Optional[int]): The maximum number of operations to fetch in each network call. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): When there are multiple pages of results, a pagination token is returned in the response. The token can be used - to fetch the next page of results. [optional] - - Returns: - Returns a generator that yields each import operation. It automatically handles pagination tokens on your behalf so you can - easily iterate over all results. The `list_imports` method accepts all of the same arguments as list_imports_paginated - - ```python - for op in index.list_imports(): - print(op) - ``` - - You can convert the generator into a list by wrapping the generator in a call to the built-in `list` function: - - ```python - operations = list(index.list_imports()) - ``` - - You should be cautious with this approach because it will fetch all operations at once, which could be a large number - of network calls and a lot of memory to hold the results. - """ - done = False - while not done: - results = self.list_imports_paginated(**kwargs) - if len(results.data) > 0: - for op in results.data: - yield op - - if results.pagination: - kwargs.update({"pagination_token": results.pagination.next}) - else: - done = True - - def list_imports_paginated( - self, limit: Optional[int] = None, pagination_token: Optional[str] = None, **kwargs - ) -> ListImportsResponse: - """ - Args: - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - - Returns: ListImportsResponse object which contains the list of operations as ImportModel objects, pagination information, - and usage showing the number of read_units consumed. - - The list_imports_paginated operation returns information about import operations. - It returns operations in a paginated form, with a pagination token to fetch the next page of results. - - Consider using the `list_imports` method to avoid having to handle pagination tokens manually. - - Examples: - >>> results = index.list_imports_paginated(limit=5) - >>> results.pagination.next - eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9 - >>> results.data[0] - { - "id": "6", - "uri": "s3://dev-bulk-import-datasets-pub/10-records-dim-10/", - "status": "Completed", - "percent_complete": 100.0, - "records_imported": 10, - "created_at": "2024-09-06T14:52:02.567776+00:00", - "finished_at": "2024-09-06T14:52:28.130717+00:00" - } - >>> next_results = index.list_imports_paginated(limit=5, pagination_token=results.pagination.next) - """ - args_dict = BulkImportRequestFactory.list_imports_paginated_args( - limit=limit, pagination_token=pagination_token, **kwargs - ) - return self.__import_operations_api.list_bulk_imports(**args_dict) - - def describe_import(self, id: str) -> ImportModel: - """ - Args: - id (str): The id of the import operation. This value is returned when - starting an import, and can be looked up using list_imports. - - Returns: - `ImportModel`: An object containing operation id, status, and other details. - - describe_import is used to get detailed information about a specific import operation. - """ - args = BulkImportRequestFactory.describe_import_args(id=id) - return self.__import_operations_api.describe_bulk_import(**args) - - def cancel_import(self, id: str): - """Cancel an import operation. - - Args: - id (str): The id of the import operation to cancel. - """ - args = BulkImportRequestFactory.cancel_import_args(id=id) - return self.__import_operations_api.cancel_bulk_import(**args) diff --git a/pinecone/data/features/bulk_import/bulk_import_asyncio.py b/pinecone/data/features/bulk_import/bulk_import_asyncio.py deleted file mode 100644 index 0cd674d58..000000000 --- a/pinecone/data/features/bulk_import/bulk_import_asyncio.py +++ /dev/null @@ -1,143 +0,0 @@ -from typing import Optional, Literal, AsyncIterator, List - -from pinecone.core.openapi.db_data.api.bulk_operations_api import AsyncioBulkOperationsApi - -from pinecone.utils import install_json_repr_override - -from pinecone.core.openapi.db_data.models import ( - StartImportResponse, - ListImportsResponse, - ImportModel, -) - -from .bulk_import_request_factory import BulkImportRequestFactory - -for m in [StartImportResponse, ListImportsResponse, ImportModel]: - install_json_repr_override(m) - - -class ImportFeatureMixinAsyncio: - def __init__(self, api_client, **kwargs) -> None: - self.__import_operations_api = AsyncioBulkOperationsApi(api_client) - - async def start_import( - self, - uri: str, - integration_id: Optional[str] = None, - error_mode: Optional[Literal["CONTINUE", "ABORT"]] = "CONTINUE", - ) -> StartImportResponse: - """ - Args: - uri (str): The URI of the data to import. The URI must start with the scheme of a supported storage provider. - integration_id (Optional[str], optional): If your bucket requires authentication to access, you need to pass the id of your storage integration using this property. Defaults to None. - error_mode: Defaults to "CONTINUE". If set to "CONTINUE", the import operation will continue even if some - records fail to import. Pass "ABORT" to stop the import operation if any records fail to import. - - Returns: - `StartImportResponse`: Contains the id of the import operation. - - Import data from a storage provider into an index. The uri must start with the scheme of a supported - storage provider. For buckets that are not publicly readable, you will also need to separately configure - a storage integration and pass the integration id. - - Examples: - >>> from pinecone import Pinecone - >>> index = Pinecone().IndexAsyncio(host="example-index.svc.aped-4627-b74a.pinecone.io") - >>> await index.start_import(uri="s3://bucket-name/path/to/data.parquet") - { id: "1" } - - """ - req = BulkImportRequestFactory.start_import_request( - uri=uri, integration_id=integration_id, error_mode=error_mode - ) - return await self.__import_operations_api.start_bulk_import(req) - - async def list_imports(self, **kwargs) -> AsyncIterator[List[ImportModel]]: - """ - Args: - limit (Optional[int]): The maximum number of operations to fetch in each network call. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): When there are multiple pages of results, a pagination token is returned in the response. The token can be used - to fetch the next page of results. [optional] - - Returns an async generator that yields each import operation. It automatically handles pagination tokens on your behalf so you can - easily iterate over all results. The `list_imports` method accepts all of the same arguments as `list_imports_paginated` - - ```python - async for op in index.list_imports(): - print(op) - ``` - """ - done = False - while not done: - results = await self.list_imports_paginated(**kwargs) - if len(results.data) > 0: - for op in results.data: - yield op - - if results.pagination: - kwargs.update({"pagination_token": results.pagination.next}) - else: - done = True - - async def list_imports_paginated( - self, limit: Optional[int] = None, pagination_token: Optional[str] = None, **kwargs - ) -> ListImportsResponse: - """ - Args: - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - - Returns: - `ListImportsResponse` object which contains the list of operations as ImportModel objects, pagination information, - and usage showing the number of read_units consumed. - - The `list_imports_paginated` operation returns information about import operations. - It returns operations in a paginated form, with a pagination token to fetch the next page of results. - - Consider using the `list_imports` method to avoid having to handle pagination tokens manually. - - Examples: - >>> results = await index.list_imports_paginated(limit=5) - >>> results.pagination.next - eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9 - >>> results.data[0] - { - "id": "6", - "uri": "s3://dev-bulk-import-datasets-pub/10-records-dim-10/", - "status": "Completed", - "percent_complete": 100.0, - "records_imported": 10, - "created_at": "2024-09-06T14:52:02.567776+00:00", - "finished_at": "2024-09-06T14:52:28.130717+00:00" - } - >>> next_results = await index.list_imports_paginated(limit=5, pagination_token=results.pagination.next) - - """ - args_dict = BulkImportRequestFactory.list_imports_paginated_args( - limit=limit, pagination_token=pagination_token, **kwargs - ) - return await self.__import_operations_api.list_bulk_imports(**args_dict) - - async def describe_import(self, id: str) -> ImportModel: - """ - Args: - id (str): The id of the import operation. This value is returned when - starting an import, and can be looked up using list_imports. - - Returns: - ImportModel: An object containing operation id, status, and other details. - - `describe_import` is used to get detailed information about a specific import operation. - """ - args = BulkImportRequestFactory.describe_import_args(id=id) - return await self.__import_operations_api.describe_bulk_import(**args) - - async def cancel_import(self, id: str): - """Cancel an import operation. - - Args: - id (str): The id of the import operation to cancel. - """ - args = BulkImportRequestFactory.cancel_import_args(id=id) - return await self.__import_operations_api.cancel_bulk_import(**args) diff --git a/pinecone/data/features/bulk_import/bulk_import_request_factory.py b/pinecone/data/features/bulk_import/bulk_import_request_factory.py deleted file mode 100644 index fd729efcd..000000000 --- a/pinecone/data/features/bulk_import/bulk_import_request_factory.py +++ /dev/null @@ -1,67 +0,0 @@ -from enum import Enum -from typing import Optional, TypedDict, Any, Union - -from pinecone.core.openapi.db_data.models import ( - StartImportRequest, - ImportErrorMode as ImportErrorModeClass, -) - -from pinecone.utils import parse_non_empty_args, convert_enum_to_string - - -class ImportErrorMode(Enum): - CONTINUE = "CONTINUE" - ABORT = "ABORT" - - -class DescribeImportArgs(TypedDict, total=False): - id: str - - -class CancelImportArgs(TypedDict, total=False): - id: str - - -class BulkImportRequestFactory: - @staticmethod - def start_import_request( - uri: str, - integration_id: Optional[str] = None, - error_mode: Optional[Union[ImportErrorMode, str]] = "CONTINUE", - ) -> StartImportRequest: - if error_mode is None: - error_mode = "CONTINUE" - error_mode_str = convert_enum_to_string(error_mode).lower() - valid_error_modes = [mode.value.lower() for mode in ImportErrorMode] - if error_mode_str not in valid_error_modes: - raise ValueError( - f"Invalid error_mode: {error_mode}. Must be one of {valid_error_modes}" - ) - - args_dict = parse_non_empty_args( - [ - ("uri", uri), - ("integration_id", integration_id), - ("error_mode", ImportErrorModeClass(on_error=error_mode_str)), - ] - ) - - return StartImportRequest(**args_dict) - - @staticmethod - def list_imports_paginated_args( - limit: Optional[int] = None, pagination_token: Optional[str] = None, **kwargs - ) -> dict[str, Any]: - return parse_non_empty_args([("limit", limit), ("pagination_token", pagination_token)]) - - @staticmethod - def describe_import_args(id: str) -> DescribeImportArgs: - if isinstance(id, int): - id = str(id) - return {"id": id} - - @staticmethod - def cancel_import_args(id: str) -> CancelImportArgs: - if isinstance(id, int): - id = str(id) - return {"id": id} diff --git a/pinecone/data/features/inference/__init__.py b/pinecone/data/features/inference/__init__.py deleted file mode 100644 index 30e933301..000000000 --- a/pinecone/data/features/inference/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .repl_overrides import install_repl_overrides -from .inference import Inference -from .inference_asyncio import AsyncioInference -from .inference_request_builder import RerankModel, EmbedModel - -install_repl_overrides() diff --git a/pinecone/data/features/inference/inference.py b/pinecone/data/features/inference/inference.py deleted file mode 100644 index 8fbaaa0c5..000000000 --- a/pinecone/data/features/inference/inference.py +++ /dev/null @@ -1,168 +0,0 @@ -import logging -from typing import Optional, Dict, List, Union, Any - -from pinecone.openapi_support import ApiClient -from pinecone.core.openapi.inference.apis import InferenceApi -from .models import EmbeddingsList, RerankResult -from pinecone.core.openapi.inference import API_VERSION -from pinecone.utils import setup_openapi_client, PluginAware - - -from .inference_request_builder import ( - InferenceRequestBuilder, - EmbedModel as EmbedModelEnum, - RerankModel as RerankModelEnum, -) - -logger = logging.getLogger(__name__) -""" @private """ - - -class Inference(PluginAware): - """ - The `Inference` class configures and uses the Pinecone Inference API to generate embeddings and - rank documents. - - :param config: A `pinecone.config.Config` object, configured and built in the Pinecone class. - :type config: `pinecone.config.Config`, required - """ - - EmbedModel = EmbedModelEnum - RerankModel = RerankModelEnum - - def __init__(self, config, openapi_config, **kwargs) -> None: - self.config = config - self.openapi_config = openapi_config - self.pool_threads = kwargs.get("pool_threads", 1) - - self.__inference_api = setup_openapi_client( - api_client_klass=ApiClient, - api_klass=InferenceApi, - config=config, - openapi_config=openapi_config, - pool_threads=kwargs.get("pool_threads", 1), - api_version=API_VERSION, - ) - self.load_plugins( - config=self.config, openapi_config=self.openapi_config, pool_threads=self.pool_threads - ) - - def embed( - self, - model: Union[EmbedModelEnum, str], - inputs: Union[str, List[Dict], List[str]], - parameters: Optional[Dict[str, Any]] = None, - ) -> EmbeddingsList: - """ - Generates embeddings for the provided inputs using the specified model and (optional) parameters. - - :param model: The model to use for generating embeddings. - :type model: str, required - - :param inputs: A list of items to generate embeddings for. - :type inputs: list, required - - :param parameters: A dictionary of parameters to use when generating embeddings. - :type parameters: dict, optional - - :return: EmbeddingsList object with keys `data`, `model`, and `usage`. The `data` key contains a list of - `n` embeddings, where `n` = len(inputs) and type(n) = Embedding. Precision of returned embeddings is either - float16 or float32, with float32 being the default. `model` key is the model used to generate the embeddings. - `usage` key contains the total number of tokens used at request-time. - - Example: - >>> inputs = ["Who created the first computer?"] - >>> outputs = pc.inference.embed(model="multilingual-e5-large", inputs=inputs, parameters={"input_type": "passage", "truncate": "END"}) - >>> print(outputs) - EmbeddingsList( - model='multilingual-e5-large', - data=[ - {'values': [0.1, ...., 0.2]}, - ], - usage={'total_tokens': 6} - ) - """ - request_body = InferenceRequestBuilder.embed_request( - model=model, inputs=inputs, parameters=parameters - ) - resp = self.__inference_api.embed(embed_request=request_body) - return EmbeddingsList(resp) - - def rerank( - self, - model: Union[RerankModelEnum, str], - query: str, - documents: Union[List[str], List[Dict[str, Any]]], - rank_fields: List[str] = ["text"], - return_documents: bool = True, - top_n: Optional[int] = None, - parameters: Optional[Dict[str, Any]] = None, - ) -> RerankResult: - """ - Rerank documents with associated relevance scores that represent the relevance of each document - to the provided query using the specified model. - - :param model: The model to use for reranking. - :type model: str, required - - :param query: The query to compare with documents. - :type query: str, required - - :param documents: A list of documents or strings to rank. - :type documents: list, required - - :param rank_fields: A list of document fields to use for ranking. Defaults to ["text"]. - :type rank_fields: list, optional - - :param return_documents: Whether to include the documents in the response. Defaults to True. - :type return_documents: bool, optional - - :param top_n: How many documents to return. Defaults to len(documents). - :type top_n: int, optional - - :param parameters: A dictionary of parameters to use when ranking documents. - :type parameters: dict, optional - - :return: RerankResult object with keys `data` and `usage`. The `data` key contains a list of - `n` documents, where `n` = `top_n` and type(n) = Document. The documents are sorted in order of - relevance, with the first being the most relevant. The `index` field can be used to locate the document - relative to the list of documents specified in the request. Each document contains a `score` key - representing how close the document relates to the query. - - Example: - >>> result = pc.inference.rerank( - model="bge-reranker-v2-m3", - query="Tell me about tech companies", - documents=[ - "Apple is a popular fruit known for its sweetness and crisp texture.", - "Software is still eating the world.", - "Many people enjoy eating apples as a healthy snack.", - "Acme Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - "An apple a day keeps the doctor away, as the saying goes.", - ], - top_n=2, - return_documents=True, - ) - >>> print(result) - RerankResult( - model='bge-reranker-v2-m3', - data=[ - { index=3, score=0.020980744, - document={text="Acme Inc. has rev..."} }, - { index=1, score=0.00034015716, - document={text="Software is still..."} } - ], - usage={'rerank_units': 1} - ) - """ - rerank_request = InferenceRequestBuilder.rerank( - model=model, - query=query, - documents=documents, - rank_fields=rank_fields, - return_documents=return_documents, - top_n=top_n, - parameters=parameters, - ) - resp = self.__inference_api.rerank(rerank_request=rerank_request) - return RerankResult(resp) diff --git a/pinecone/data/features/inference/inference_asyncio.py b/pinecone/data/features/inference/inference_asyncio.py deleted file mode 100644 index a78f1d6e5..000000000 --- a/pinecone/data/features/inference/inference_asyncio.py +++ /dev/null @@ -1,147 +0,0 @@ -from typing import Optional, Dict, List, Union, Any - -from pinecone.core.openapi.inference.api.inference_api import AsyncioInferenceApi -from .models import EmbeddingsList, RerankResult - -from .inference_request_builder import ( - InferenceRequestBuilder, - EmbedModel as EmbedModelEnum, - RerankModel as RerankModelEnum, -) - - -class AsyncioInference: - """ - The `Inference` class configures and uses the Pinecone Inference API to generate embeddings and - rank documents. - - :param config: A `pinecone.config.Config` object, configured and built in the Pinecone class. - :type config: `pinecone.config.Config`, required - """ - - EmbedModel = EmbedModelEnum - RerankModel = RerankModelEnum - - def __init__(self, api_client, **kwargs) -> None: - self.api_client = api_client - self.__inference_api = AsyncioInferenceApi(api_client) - - async def embed( - self, - model: str, - inputs: Union[str, List[Dict], List[str]], - parameters: Optional[Dict[str, Any]] = None, - ) -> EmbeddingsList: - """ - Generates embeddings for the provided inputs using the specified model and (optional) parameters. - - :param model: The model to use for generating embeddings. - :type model: str, required - - :param inputs: A list of items to generate embeddings for. - :type inputs: list, required - - :param parameters: A dictionary of parameters to use when generating embeddings. - :type parameters: dict, optional - - :return: EmbeddingsList object with keys `data`, `model`, and `usage`. The `data` key contains a list of - `n` embeddings, where `n` = len(inputs) and type(n) = Embedding. Precision of returned embeddings is either - float16 or float32, with float32 being the default. `model` key is the model used to generate the embeddings. - `usage` key contains the total number of tokens used at request-time. - - Example: - >>> inputs = ["Who created the first computer?"] - >>> outputs = await pc.inference.embed(model="multilingual-e5-large", inputs=inputs, parameters={"input_type": "passage", "truncate": "END"}) - >>> print(outputs) - EmbeddingsList( - model='multilingual-e5-large', - data=[ - {'values': [0.1, ...., 0.2]}, - ], - usage={'total_tokens': 6} - ) - """ - request_body = InferenceRequestBuilder.embed_request( - model=model, inputs=inputs, parameters=parameters - ) - resp = await self.__inference_api.embed(embed_request=request_body) - return EmbeddingsList(resp) - - async def rerank( - self, - model: str, - query: str, - documents: Union[List[str], List[Dict[str, Any]]], - rank_fields: List[str] = ["text"], - return_documents: bool = True, - top_n: Optional[int] = None, - parameters: Optional[Dict[str, Any]] = None, - ) -> RerankResult: - """ - Rerank documents with associated relevance scores that represent the relevance of each document - to the provided query using the specified model. - - :param model: The model to use for reranking. - :type model: str, required - - :param query: The query to compare with documents. - :type query: str, required - - :param documents: A list of documents or strings to rank. - :type documents: list, required - - :param rank_fields: A list of document fields to use for ranking. Defaults to ["text"]. - :type rank_fields: list, optional - - :param return_documents: Whether to include the documents in the response. Defaults to True. - :type return_documents: bool, optional - - :param top_n: How many documents to return. Defaults to len(documents). - :type top_n: int, optional - - :param parameters: A dictionary of parameters to use when ranking documents. - :type parameters: dict, optional - - :return: RerankResult object with keys `data` and `usage`. The `data` key contains a list of - `n` documents, where `n` = `top_n` and type(n) = Document. The documents are sorted in order of - relevance, with the first being the most relevant. The `index` field can be used to locate the document - relative to the list of documents specified in the request. Each document contains a `score` key - representing how close the document relates to the query. - - Example: - >>> result = await pc.inference.rerank( - model="bge-reranker-v2-m3", - query="Tell me about tech companies", - documents=[ - "Apple is a popular fruit known for its sweetness and crisp texture.", - "Software is still eating the world.", - "Many people enjoy eating apples as a healthy snack.", - "Acme Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - "An apple a day keeps the doctor away, as the saying goes.", - ], - top_n=2, - return_documents=True, - ) - >>> print(result) - RerankResult( - model='bge-reranker-v2-m3', - data=[ - { index=3, score=0.020980744, - document={text="Acme Inc. has rev..."} }, - { index=1, score=0.00034015716, - document={text="Software is still..."} } - ], - usage={'rerank_units': 1} - ) - """ - rerank_request = InferenceRequestBuilder.rerank( - model=model, - query=query, - documents=documents, - rank_fields=rank_fields, - return_documents=return_documents, - top_n=top_n, - parameters=parameters, - ) - resp = await self.__inference_api.rerank(rerank_request=rerank_request) - return RerankResult(resp) diff --git a/pinecone/data/features/inference/inference_request_builder.py b/pinecone/data/features/inference/inference_request_builder.py deleted file mode 100644 index 3e10c1fec..000000000 --- a/pinecone/data/features/inference/inference_request_builder.py +++ /dev/null @@ -1,87 +0,0 @@ -from enum import Enum -from typing import Optional, Union, List, Dict, Any - -from pinecone.core.openapi.inference.models import ( - EmbedRequest, - EmbedRequestInputs, - Document, - RerankRequest, -) -from pinecone.utils import convert_enum_to_string - - -class EmbedModel(Enum): - Multilingual_E5_Large = "multilingual-e5-large" - Pinecone_Sparse_English_V0 = "pinecone-sparse-english-v0" - - -class RerankModel(Enum): - Bge_Reranker_V2_M3 = "bge-reranker-v2-m3" - Cohere_Rerank_3_5 = "cohere-rerank-3.5" - Pinecone_Rerank_V0 = "pinecone-rerank-v0" - - -class InferenceRequestBuilder: - @staticmethod - def embed_request( - model: Union[EmbedModel, str], - inputs: Union[str, List[Dict], List[str]], - parameters: Optional[Dict[str, Any]] = None, - ) -> EmbedRequest: - model = convert_enum_to_string(model) - embeddings_inputs: List[EmbedRequestInputs] = [] - if isinstance(inputs, str): - embeddings_inputs = [EmbedRequestInputs(text=inputs)] - elif isinstance(inputs, list) and len(inputs) > 0: - if isinstance(inputs[0], str): - embeddings_inputs = [EmbedRequestInputs(text=i) for i in inputs] - elif isinstance(inputs[0], dict): - embeddings_inputs = [EmbedRequestInputs(**i) for i in inputs] - else: - raise Exception("Invalid type for variable 'inputs'") - else: - raise Exception("Invalid type for variable 'inputs'") - - if parameters: - return EmbedRequest(model=model, inputs=embeddings_inputs, parameters=parameters) - else: - return EmbedRequest(model=model, inputs=embeddings_inputs) - - @staticmethod - def rerank( - model: Union[RerankModel, str], - query: str, - documents: Union[List[str], List[Dict[str, Any]]], - rank_fields: List[str] = ["text"], - return_documents: bool = True, - top_n: Optional[int] = None, - parameters: Optional[Dict[str, Any]] = None, - ) -> RerankRequest: - if isinstance(model, RerankModel): - model = model.value - else: - model = str(model) - - if isinstance(documents, list) and len(documents) > 0: - if isinstance(documents[0], str): - documents = [Document(text=doc) for doc in documents] - elif isinstance(documents[0], dict): - documents = [Document(**doc) for doc in documents] - else: - raise Exception("Invalid type for variable 'documents'") - else: - raise Exception("Invalid type or value for variable 'documents'") - - args: Dict[str, Any] = { - "model": model, - "query": query, - "documents": documents, - "rank_fields": rank_fields, - "return_documents": return_documents, - } - if top_n is not None: - args["top_n"] = top_n - if parameters is not None: - args["parameters"] = parameters - - return RerankRequest(**args) diff --git a/pinecone/data/features/inference/models/__init__.py b/pinecone/data/features/inference/models/__init__.py deleted file mode 100644 index b9a18aeb6..000000000 --- a/pinecone/data/features/inference/models/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .embedding_list import EmbeddingsList -from .rerank_result import RerankResult diff --git a/pinecone/data/features/inference/models/embedding_list.py b/pinecone/data/features/inference/models/embedding_list.py deleted file mode 100644 index f28a2f822..000000000 --- a/pinecone/data/features/inference/models/embedding_list.py +++ /dev/null @@ -1,29 +0,0 @@ -from pinecone.core.openapi.inference.models import EmbeddingsList as OpenAPIEmbeddingsList - - -class EmbeddingsList: - """ - A list of embeddings. - """ - - def __init__(self, embeddings_list: OpenAPIEmbeddingsList): - self.embeddings_list = embeddings_list - self.current = 0 - - def __getitem__(self, index): - return self.embeddings_list.get("data")[index] - - def __len__(self): - return len(self.embeddings_list.get("data")) - - def __iter__(self): - return iter(self.embeddings_list.get("data")) - - def __str__(self): - return str(self.embeddings_list) - - def __repr__(self): - return repr(self.embeddings_list) - - def __getattr__(self, attr): - return getattr(self.embeddings_list, attr) diff --git a/pinecone/data/features/inference/models/rerank_result.py b/pinecone/data/features/inference/models/rerank_result.py deleted file mode 100644 index 2a72527af..000000000 --- a/pinecone/data/features/inference/models/rerank_result.py +++ /dev/null @@ -1,19 +0,0 @@ -from pinecone.core.openapi.inference.models import RerankResult as OpenAPIRerankResult - - -class RerankResult: - """ - A wrapper around OpenAPIRerankResult. - """ - - def __init__(self, rerank_result: OpenAPIRerankResult): - self.rerank_result = rerank_result - - def __str__(self): - return str(self.rerank_result) - - def __repr__(self): - return repr(self.rerank_result) - - def __getattr__(self, attr): - return getattr(self.rerank_result, attr) diff --git a/pinecone/data/features/inference/repl_overrides.py b/pinecone/data/features/inference/repl_overrides.py deleted file mode 100644 index 8c6795429..000000000 --- a/pinecone/data/features/inference/repl_overrides.py +++ /dev/null @@ -1,106 +0,0 @@ -from pinecone.core.openapi.inference.models import ( - EmbeddingsList as OpenAPIEmbeddingsList, - SparseEmbedding as OpenAPISparseEmbedding, - DenseEmbedding as OpenAPIDenseEmbedding, - Document as OpenAPIDocument, - RerankResult as OpenAPIRerankResult, - RankedDocument as OpenAPIRankedDocument, -) - - -def present_list(mylist) -> str: - if not mylist: - return "[]" - if len(mylist) <= 5: - # Show list as usual when fewer than 5 items. - # This number is arbitrary and can be adjusted - # but it seems silly to show the abbreviated - # message with (2 more) or whatever when the - # number of items is so small and it's no problem - # to display the real values. - return f"[{', '.join(repr(x) for x in mylist)}]" - first_part = ", ".join(repr(x) for x in mylist[:2]) - last_part = ", ".join(repr(x) for x in mylist[-2:]) - formatted_values = f"[{first_part}, ..., {last_part}]" - return formatted_values - - -def sparse_embedding_to_str(self: OpenAPISparseEmbedding): - formatted_sparse_values = present_list(self.sparse_values) - formatted_sparse_indices = present_list(self.sparse_indices) - formatted_sparse_tokens = present_list(self.sparse_tokens) - parts = [ - "'vector_type': sparse", - f"'sparse_values': {formatted_sparse_values}", - f"'sparse_indices': {formatted_sparse_indices}", - ] - if self.sparse_tokens: - parts.append(f"'sparse_tokens': {formatted_sparse_tokens}") - return "{{{}}}".format(", ".join(parts)) - - -def dense_embedding_to_str(self: OpenAPIDenseEmbedding): - formatted_values = present_list(self.values) - parts = ["'vector_type': dense", f"'values': {formatted_values}"] - return "{{{}}}".format(", ".join(parts)) - - -def embedding_list_to_string(self: OpenAPIEmbeddingsList): - if len(self.data) == 0: - formatted_embeddings = "[]" - elif len(self.data) <= 5: - formatted_embeddings = ( - "[\n " + ",\n ".join([embedding.to_str() for embedding in self.data]) + "\n ]" - ) - else: - omitted_msg = f"... ({len(self.data) - 4} more embeddings) ..." - items_to_show = ( - [e.to_str() for e in self.data[:2]] - + [omitted_msg] - + [e.to_str() for e in self.data[-2:]] - ) - formatted_embeddings = "[\n " + ",\n ".join(items_to_show) + "\n ]" - - return """EmbeddingsList( - model='{self.model}', - vector_type='{self.vector_type}', - data={formatted_embeddings}, - usage={self.usage} -)""".format(self=self, formatted_embeddings=formatted_embeddings) - - -def rank_result_document_to_str(self: OpenAPIDocument): - return ",\n ".join([f"{k}={repr(v)}" for k, v in self.to_dict().items()]) - - -def rank_result_item_to_str(self: OpenAPIRankedDocument): - if self.document is None: - document_str = "" - else: - document_str = f"document={{\n {self.document}\n }}" - - return f"{{\n index={self.index},\n score={self.score},\n {document_str}\n }}" - - -def rerank_result_to_str(self: OpenAPIRerankResult): - if len(self.data) == 0: - formatted_rerank = "[]" - else: - formatted_rerank = ( - "[" + ",".join([rank_result_item.to_str() for rank_result_item in self.data]) + "]" - ) - - return f"""RerankResult( - model='{self.model}', - data={formatted_rerank}, - usage={self.usage} -)""" - - -def install_repl_overrides(): - OpenAPIDenseEmbedding.to_str = dense_embedding_to_str - OpenAPISparseEmbedding.to_str = sparse_embedding_to_str - OpenAPIEmbeddingsList.to_str = embedding_list_to_string - OpenAPIDocument.to_str = rank_result_document_to_str - OpenAPIRankedDocument.to_str = rank_result_item_to_str - OpenAPIRerankResult.to_str = rerank_result_to_str diff --git a/pinecone/data/import_error.py b/pinecone/data/import_error.py deleted file mode 100644 index d0b7d1ecb..000000000 --- a/pinecone/data/import_error.py +++ /dev/null @@ -1,62 +0,0 @@ -class IndexClientInstantiationError(Exception): - def __init__(self, index_args, index_kwargs) -> None: - formatted_args = ", ".join(map(repr, index_args)) - formatted_kwargs = ", ".join(f"{key}={repr(value)}" for key, value in index_kwargs.items()) - combined_args = ", ".join([a for a in [formatted_args, formatted_kwargs] if a.strip()]) - - self.message = f"""You are attempting to access the Index client directly from the pinecone module. The Index client must be instantiated through the parent Pinecone client instance so that it can inherit shared configurations such as API key. - - INCORRECT USAGE: - ``` - import pinecone - - pc = pinecone.Pinecone(api_key='your-api-key') - index = pinecone.Index({combined_args}) - ``` - - CORRECT USAGE: - ``` - from pinecone import Pinecone - - pc = Pinecone(api_key='your-api-key') - index = pc.Index({combined_args}) - ``` - """ - super().__init__(self.message) - - -class InferenceInstantiationError(Exception): - def __init__(self) -> None: - self.message = """You are attempting to access the Inference client directly from the pinecone module. Inference functionality such as `embed` and `rerank` should only be accessed through the parent Pinecone client instance. - - INCORRECT USAGE: - ``` - import pinecone - - pinecone.Inference().embed(...) - ``` - - CORRECT USAGE: - ``` - from pinecone import Pinecone - - pc = Pinecone(api_key='your-api-key') - - embeddings = pc.inference.embed( - model='multilingual-e5-large', - inputs=["The quick brown fox jumps over the lazy dog.", "lorem ipsum"], - parameters={"input_type": "query", "truncate": "END"}, - ) - ``` - """ - super().__init__(self.message) - - -class Index: - def __init__(self, *args, **kwargs) -> None: - raise IndexClientInstantiationError(args, kwargs) - - -class Inference: - def __init__(self, *args, **kwargs) -> None: - raise InferenceInstantiationError() diff --git a/pinecone/data/index.py b/pinecone/data/index.py deleted file mode 100644 index ebd5cecd4..000000000 --- a/pinecone/data/index.py +++ /dev/null @@ -1,435 +0,0 @@ -from pinecone.utils.tqdm import tqdm - -import logging -import json -from typing import Union, List, Optional, Dict, Any, Literal - -from pinecone.config import ConfigBuilder - -from pinecone.openapi_support import ApiClient -from pinecone.core.openapi.db_data.api.vector_operations_api import VectorOperationsApi -from pinecone.core.openapi.db_data import API_VERSION -from pinecone.core.openapi.db_data.models import ( - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, - UpsertResponse, - ListResponse, - SearchRecordsResponse, -) -from .dataclasses import Vector, SparseValues, FetchResponse, SearchQuery, SearchRerank -from .interfaces import IndexInterface -from .request_factory import IndexRequestFactory -from .features.bulk_import import ImportFeatureMixin -from .types import ( - SparseVectorTypedDict, - VectorTypedDict, - VectorMetadataTypedDict, - VectorTuple, - VectorTupleWithMetadata, - FilterTypedDict, - SearchRerankTypedDict, - SearchQueryTypedDict, -) -from ..utils import ( - setup_openapi_client, - parse_non_empty_args, - validate_and_convert_errors, - filter_dict, - PluginAware, -) -from .query_results_aggregator import QueryResultsAggregator, QueryNamespacesResults -from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS - -from multiprocessing.pool import ApplyResult -from multiprocessing import cpu_count -from concurrent.futures import as_completed - - -logger = logging.getLogger(__name__) -""" @private """ - - -def parse_query_response(response: QueryResponse): - """@private""" - response._data_store.pop("results", None) - return response - - -class Index(IndexInterface, ImportFeatureMixin, PluginAware): - """ - A client for interacting with a Pinecone index via REST API. - For improved performance, use the Pinecone GRPC index client. - """ - - def __init__( - self, - api_key: str, - host: str, - pool_threads: Optional[int] = None, - additional_headers: Optional[Dict[str, str]] = {}, - openapi_config=None, - **kwargs, - ): - self.config = ConfigBuilder.build( - api_key=api_key, host=host, additional_headers=additional_headers, **kwargs - ) - """ @private """ - self.openapi_config = ConfigBuilder.build_openapi_config(self.config, openapi_config) - """ @private """ - - if pool_threads is None: - self.pool_threads = 5 * cpu_count() - """ @private """ - else: - self.pool_threads = pool_threads - """ @private """ - - if kwargs.get("connection_pool_maxsize", None): - self.openapi_config.connection_pool_maxsize = kwargs.get("connection_pool_maxsize") - - self._vector_api = setup_openapi_client( - api_client_klass=ApiClient, - api_klass=VectorOperationsApi, - config=self.config, - openapi_config=self.openapi_config, - pool_threads=pool_threads, - api_version=API_VERSION, - ) - - self._api_client = self._vector_api.api_client - - # Pass the same api_client to the ImportFeatureMixin - super().__init__(api_client=self._api_client) - - self.load_plugins( - config=self.config, openapi_config=self.openapi_config, pool_threads=self.pool_threads - ) - - def _openapi_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: - return filter_dict(kwargs, OPENAPI_ENDPOINT_PARAMS) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self._vector_api.api_client.close() - - def close(self): - self._vector_api.api_client.close() - - @validate_and_convert_errors - def upsert( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str] = None, - batch_size: Optional[int] = None, - show_progress: bool = True, - **kwargs, - ) -> UpsertResponse: - _check_type = kwargs.pop("_check_type", True) - - if kwargs.get("async_req", False) and batch_size is not None: - raise ValueError( - "async_req is not supported when batch_size is provided." - "To upsert in parallel, please follow: " - "https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel" - ) - - if batch_size is None: - return self._upsert_batch(vectors, namespace, _check_type, **kwargs) - - if not isinstance(batch_size, int) or batch_size <= 0: - raise ValueError("batch_size must be a positive integer") - - pbar = tqdm(total=len(vectors), disable=not show_progress, desc="Upserted vectors") - total_upserted = 0 - for i in range(0, len(vectors), batch_size): - batch_result = self._upsert_batch( - vectors[i : i + batch_size], namespace, _check_type, **kwargs - ) - pbar.update(batch_result.upserted_count) - # we can't use here pbar.n for the case show_progress=False - total_upserted += batch_result.upserted_count - - return UpsertResponse(upserted_count=total_upserted) - - def _upsert_batch( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str], - _check_type: bool, - **kwargs, - ) -> UpsertResponse: - return self._vector_api.upsert_vectors( - IndexRequestFactory.upsert_request(vectors, namespace, _check_type, **kwargs), - **self._openapi_kwargs(kwargs), - ) - - @staticmethod - def _iter_dataframe(df, batch_size): - for i in range(0, len(df), batch_size): - batch = df.iloc[i : i + batch_size].to_dict(orient="records") - yield batch - - @validate_and_convert_errors - def upsert_from_dataframe( - self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True - ) -> UpsertResponse: - try: - import pandas as pd - except ImportError: - raise RuntimeError( - "The `pandas` package is not installed. Please install pandas to use `upsert_from_dataframe()`" - ) - - if not isinstance(df, pd.DataFrame): - raise ValueError(f"Only pandas dataframes are supported. Found: {type(df)}") - - pbar = tqdm(total=len(df), disable=not show_progress, desc="sending upsert requests") - results = [] - for chunk in self._iter_dataframe(df, batch_size=batch_size): - res = self.upsert(vectors=chunk, namespace=namespace) - pbar.update(len(chunk)) - results.append(res) - - upserted_count = 0 - for res in results: - upserted_count += res.upserted_count - - return UpsertResponse(upserted_count=upserted_count) - - def upsert_records(self, namespace: str, records: List[Dict]): - args = IndexRequestFactory.upsert_records_args(namespace=namespace, records=records) - self._vector_api.upsert_records_namespace(**args) - - @validate_and_convert_errors - def search( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - if namespace is None: - raise Exception("Namespace is required when searching records") - - request = IndexRequestFactory.search_request(query=query, rerank=rerank, fields=fields) - - return self._vector_api.search_records_namespace(namespace, request) - - @validate_and_convert_errors - def search_records( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - return self.search(namespace, query=query, rerank=rerank, fields=fields) - - @validate_and_convert_errors - def delete( - self, - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, - **kwargs, - ) -> Dict[str, Any]: - return self._vector_api.delete_vectors( - IndexRequestFactory.delete_request( - ids=ids, delete_all=delete_all, namespace=namespace, filter=filter, **kwargs - ), - **self._openapi_kwargs(kwargs), - ) - - @validate_and_convert_errors - def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: - args_dict = parse_non_empty_args([("namespace", namespace)]) - result = self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) - return FetchResponse( - namespace=result.namespace, - vectors={k: Vector.from_dict(v) for k, v in result.vectors.items()}, - usage=result.usage, - ) - - @validate_and_convert_errors - def query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Union[QueryResponse, ApplyResult]: - response = self._query( - *args, - top_k=top_k, - vector=vector, - id=id, - namespace=namespace, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - **kwargs, - ) - - if kwargs.get("async_req", False) or kwargs.get("async_threadpool_executor", False): - return response - else: - return parse_query_response(response) - - def _query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryResponse: - if len(args) > 0: - raise ValueError( - "The argument order for `query()` has changed; please use keyword arguments instead of positional arguments. Example: index.query(vector=[0.1, 0.2, 0.3], top_k=10, namespace='my_namespace')" - ) - - if top_k < 1: - raise ValueError("top_k must be a positive integer") - - request = IndexRequestFactory.query_request( - top_k=top_k, - vector=vector, - id=id, - namespace=namespace, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - **kwargs, - ) - return self._vector_api.query_vectors(request, **self._openapi_kwargs(kwargs)) - - @validate_and_convert_errors - def query_namespaces( - self, - vector: Optional[List[float]], - namespaces: List[str], - metric: Literal["cosine", "euclidean", "dotproduct"], - top_k: Optional[int] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, - **kwargs, - ) -> QueryNamespacesResults: - if namespaces is None or len(namespaces) == 0: - raise ValueError("At least one namespace must be specified") - if sparse_vector is None and vector is not None and len(vector) == 0: - # If querying with a vector, it must not be empty - raise ValueError("Query vector must not be empty") - - overall_topk = top_k if top_k is not None else 10 - aggregator = QueryResultsAggregator(top_k=overall_topk, metric=metric) - - target_namespaces = set(namespaces) # dedup namespaces - async_futures = [ - self.query( - vector=vector, - namespace=ns, - top_k=overall_topk, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - async_threadpool_executor=True, - _preload_content=False, - **kwargs, - ) - for ns in target_namespaces - ] - - for result in as_completed(async_futures): - raw_result = result.result() - response = json.loads(raw_result.data.decode("utf-8")) - aggregator.add_results(response) - - final_results = aggregator.get_results() - return final_results - - @validate_and_convert_errors - def update( - self, - id: str, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Dict[str, Any]: - return self._vector_api.update_vector( - IndexRequestFactory.update_request( - id=id, - values=values, - set_metadata=set_metadata, - namespace=namespace, - sparse_values=sparse_values, - **kwargs, - ), - **self._openapi_kwargs(kwargs), - ) - - @validate_and_convert_errors - def describe_index_stats( - self, filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsResponse: - return self._vector_api.describe_index_stats( - IndexRequestFactory.describe_index_stats_request(filter, **kwargs), - **self._openapi_kwargs(kwargs), - ) - - @validate_and_convert_errors - def list_paginated( - self, - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> ListResponse: - args_dict = IndexRequestFactory.list_paginated_args( - prefix=prefix, - limit=limit, - pagination_token=pagination_token, - namespace=namespace, - **kwargs, - ) - return self._vector_api.list_vectors(**args_dict, **kwargs) - - @validate_and_convert_errors - def list(self, **kwargs): - done = False - while not done: - results = self.list_paginated(**kwargs) - if len(results.vectors) > 0: - yield [v.id for v in results.vectors] - - if results.pagination: - kwargs.update({"pagination_token": results.pagination.next}) - else: - done = True diff --git a/pinecone/data/index_asyncio.py b/pinecone/data/index_asyncio.py deleted file mode 100644 index 6962e7f16..000000000 --- a/pinecone/data/index_asyncio.py +++ /dev/null @@ -1,523 +0,0 @@ -from pinecone.utils.tqdm import tqdm - - -import logging -import asyncio -import json - -from .index_asyncio_interface import IndexAsyncioInterface -from .query_results_aggregator import QueryResultsAggregator -from typing import Union, List, Optional, Dict, Any, Literal - -from pinecone.config import ConfigBuilder - -from pinecone.openapi_support import AsyncioApiClient -from pinecone.core.openapi.db_data.api.vector_operations_api import AsyncioVectorOperationsApi -from pinecone.core.openapi.db_data import API_VERSION -from pinecone.core.openapi.db_data.models import ( - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, - UpsertRequest, - UpsertResponse, - DeleteRequest, - ListResponse, - SearchRecordsResponse, -) - -from ..utils import ( - setup_async_openapi_client, - parse_non_empty_args, - validate_and_convert_errors, - filter_dict, -) -from .types import ( - SparseVectorTypedDict, - VectorTypedDict, - VectorMetadataTypedDict, - VectorTuple, - VectorTupleWithMetadata, - FilterTypedDict, - SearchQueryTypedDict, - SearchRerankTypedDict, -) -from .dataclasses import Vector, SparseValues, FetchResponse, SearchQuery, SearchRerank - -from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS -from .index import IndexRequestFactory - -from .vector_factory import VectorFactory -from .query_results_aggregator import QueryNamespacesResults -from .features.bulk_import import ImportFeatureMixinAsyncio - - -logger = logging.getLogger(__name__) -""" @private """ - -__all__ = ["_IndexAsyncio"] - -_OPENAPI_ENDPOINT_PARAMS = ( - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_check_input_type", - "_check_return_type", -) -""" @private """ - - -def parse_query_response(response: QueryResponse): - if hasattr(response, "_data_store"): - # I'm not sure, but I think this is no longer needed. At some point - # in the past the query response returned "results" instead of matches - # and then for some time it returned both keys even though "results" - # was always empty. I'm leaving this here just in case. - response._data_store.pop("results", None) - return response - - -class _IndexAsyncio(IndexAsyncioInterface, ImportFeatureMixinAsyncio): - """ - The `IndexAsyncio` class provides an asynchronous interface to interact with Pinecone indexes. - - Like the `Index` class, it provides methods to upsert, delete, fetch, and query vectors in a Pinecone index. - - The `IndexAsyncio` class is instantiated through a helper method of the `Pinecone` class. It is not meant to be instantiated directly. - This is to ensure that configuration is handled consistently across all Pinecone objects. - - ## Managing the async context - - The `IndexAsyncio` class relies on an underlying `aiohttp` `ClientSession` to make asynchronous HTTP requests. To ensure that the session is properly closed, you - should use the `async with` syntax when creating a `IndexAsyncio` object to use it as an async context manager. This will ensure that the session is properly - closed when the context is exited. - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone(api_key='YOUR_API_KEY') - async with pc.IndexAsyncio(host='example-index-dojoi3u.svc.eu-west1-gcp.pinecone.io') as idx: - # Do async things - await idx.upsert( - vectors=[ - ... - ] - ) - - asyncio.run(main()) - ``` - - As an alternative, if you prefer to avoid code with a nested appearance and are willing to manage cleanup yourself, you can await the `close()` method to close the session when you are done. - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone(api_key='YOUR_API_KEY') - idx = pc.IndexAsyncio(host='example-index-dojoi3u.svc.eu-west1-gcp.pinecone.io') - - # Do async things - await idx.describe_index_stats() - - # After you're done, you're responsible for calling this yourself - await pc.close() - - asyncio.run(main()) - ``` - - Failing to do this may result in error messages appearing from the underlyling aiohttp library. - """ - - def __init__( - self, - api_key: str, - host: str, - additional_headers: Optional[Dict[str, str]] = {}, - openapi_config=None, - **kwargs, - ): - self.config = ConfigBuilder.build( - api_key=api_key, host=host, additional_headers=additional_headers, **kwargs - ) - """ @private """ - self._openapi_config = ConfigBuilder.build_openapi_config(self.config, openapi_config) - """ @private """ - - if kwargs.get("connection_pool_maxsize", None): - self._openapi_config.connection_pool_maxsize = kwargs.get("connection_pool_maxsize") - - self._vector_api = setup_async_openapi_client( - api_client_klass=AsyncioApiClient, - api_klass=AsyncioVectorOperationsApi, - config=self.config, - openapi_config=self._openapi_config, - api_version=API_VERSION, - ) - """ @private """ - - self._api_client = self._vector_api.api_client - """ @private """ - - # Pass the same api_client to the ImportFeatureMixinAsyncio - # This is important for async context management to work correctly - super().__init__(api_client=self._api_client) - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_value, traceback): - await self._api_client.close() - - async def close(self): - """Cleanup resources used by the Pinecone Index client. - - This method should be called when the client is no longer needed so that - it can cleanup the aioahttp session and other resources. - - After close has been called, the client instance should not be used. - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone() - idx = pc.IndexAsyncio(host='example-index-dojoi3u.svc.eu-west1-gcp.pinecone.io') - await idx.upsert_records( - namespace='my-namespace', - records=[ - ... - ] - ) - - # Close the client when done - await idx.close() - - asyncio.run(main()) - ``` - - If you are using the client as a context manager, the close method is called automatically - when exiting. - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone() - async with pc.IndexAscynio(host='example-index-dojoi3u.svc.eu-west1-gcp.pinecone.io') as idx: - await idx.upsert_records( - namespace='my-namespace', - records=[ - ... - ] - ) - - # No need to call close in this case because the "async with" syntax - # automatically calls close when exiting the block. - asyncio.run(main()) - ``` - - """ - await self._api_client.close() - - @validate_and_convert_errors - async def upsert( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str] = None, - batch_size: Optional[int] = None, - show_progress: bool = True, - **kwargs, - ) -> UpsertResponse: - _check_type = kwargs.pop("_check_type", True) - - if batch_size is None: - return await self._upsert_batch(vectors, namespace, _check_type, **kwargs) - - if not isinstance(batch_size, int) or batch_size <= 0: - raise ValueError("batch_size must be a positive integer") - - upsert_tasks = [ - self._upsert_batch(vectors[i : i + batch_size], namespace, _check_type, **kwargs) - for i in range(0, len(vectors), batch_size) - ] - - total_upserted = 0 - with tqdm(total=len(vectors), desc="Upserted vectors", disable=not show_progress) as pbar: - for task in asyncio.as_completed(upsert_tasks): - res = await task - pbar.update(res.upserted_count) - total_upserted += res.upserted_count - - return UpsertResponse(upserted_count=total_upserted) - - @validate_and_convert_errors - async def _upsert_batch( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str], - _check_type: bool, - **kwargs, - ) -> UpsertResponse: - args_dict = parse_non_empty_args([("namespace", namespace)]) - - def vec_builder(v): - return VectorFactory.build(v, check_type=_check_type) - - return await self._vector_api.upsert_vectors( - UpsertRequest( - 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}, - ), - **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}, - ) - - @validate_and_convert_errors - async def upsert_from_dataframe( - self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True - ): - raise NotImplementedError("upsert_from_dataframe is not implemented for asyncio") - - @validate_and_convert_errors - async def delete( - self, - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - **kwargs, - ) -> Dict[str, Any]: - _check_type = kwargs.pop("_check_type", False) - args_dict = parse_non_empty_args( - [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter)] - ) - - return await self._vector_api.delete_vectors( - DeleteRequest( - **args_dict, - **{ - k: v - for k, v in kwargs.items() - if k not in _OPENAPI_ENDPOINT_PARAMS and v is not None - }, - _check_type=_check_type, - ), - **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}, - ) - - @validate_and_convert_errors - async def fetch( - self, ids: List[str], namespace: Optional[str] = None, **kwargs - ) -> FetchResponse: - args_dict = parse_non_empty_args([("namespace", namespace)]) - return await self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs) - - @validate_and_convert_errors - async def query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryResponse: - response = await self._query( - *args, - top_k=top_k, - vector=vector, - id=id, - namespace=namespace, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - **kwargs, - ) - return parse_query_response(response) - - async def _query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryResponse: - if len(args) > 0: - raise ValueError( - "Please use keyword arguments instead of positional arguments. Example: index.query(vector=[0.1, 0.2, 0.3], top_k=10, namespace='my_namespace')" - ) - - request = IndexRequestFactory.query_request( - top_k=top_k, - vector=vector, - id=id, - namespace=namespace, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - **kwargs, - ) - return await self._vector_api.query_vectors( - request, **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} - ) - - @validate_and_convert_errors - async def query_namespaces( - self, - namespaces: List[str], - metric: Literal["cosine", "euclidean", "dotproduct"], - top_k: Optional[int] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - vector: Optional[List[float]] = None, - sparse_vector: Optional[ - Union[SparseValues, Dict[str, Union[List[float], List[int]]]] - ] = None, - **kwargs, - ) -> QueryNamespacesResults: - if namespaces is None or len(namespaces) == 0: - raise ValueError("At least one namespace must be specified") - if sparse_vector is None and vector is not None and len(vector) == 0: - # If querying with a vector, it must not be empty - raise ValueError("Query vector must not be empty") - - overall_topk = top_k if top_k is not None else 10 - aggregator = QueryResultsAggregator(top_k=overall_topk, metric=metric) - - target_namespaces = set(namespaces) # dedup namespaces - tasks = [ - self.query( - vector=vector, - namespace=ns, - top_k=overall_topk, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - async_threadpool_executor=True, - _preload_content=False, - **kwargs, - ) - for ns in target_namespaces - ] - - for task in asyncio.as_completed(tasks): - raw_result = await task - response = json.loads(raw_result.data.decode("utf-8")) - aggregator.add_results(response) - - final_results = aggregator.get_results() - return final_results - - @validate_and_convert_errors - async def update( - self, - id: str, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Dict[str, Any]: - return await self._vector_api.update_vector( - IndexRequestFactory.update_request( - id=id, - values=values, - set_metadata=set_metadata, - namespace=namespace, - sparse_values=sparse_values, - **kwargs, - ), - **self._openapi_kwargs(kwargs), - ) - - @validate_and_convert_errors - async def describe_index_stats( - self, filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsResponse: - return await self._vector_api.describe_index_stats( - IndexRequestFactory.describe_index_stats_request(filter, **kwargs), - **self._openapi_kwargs(kwargs), - ) - - @validate_and_convert_errors - async def list_paginated( - self, - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> ListResponse: - args_dict = IndexRequestFactory.list_paginated_args( - prefix=prefix, - limit=limit, - pagination_token=pagination_token, - namespace=namespace, - **kwargs, - ) - return await self._vector_api.list_vectors(**args_dict, **kwargs) - - @validate_and_convert_errors - async def list(self, **kwargs): - done = False - while not done: - results = await self.list_paginated(**kwargs) - if len(results.vectors) > 0: - yield [v.id for v in results.vectors] - - if results.pagination: - kwargs.update({"pagination_token": results.pagination.next}) - else: - done = True - - async def upsert_records(self, namespace: str, records: List[Dict]): - args = IndexRequestFactory.upsert_records_args(namespace=namespace, records=records) - await self._vector_api.upsert_records_namespace(**args) - - async def search( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - if namespace is None: - raise Exception("Namespace is required when searching records") - - request = IndexRequestFactory.search_request(query=query, rerank=rerank, fields=fields) - - return await self._vector_api.search_records_namespace(namespace, request) - - async def search_records( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - return await self.search(namespace, query=query, rerank=rerank, fields=fields) - - def _openapi_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: - return filter_dict(kwargs, OPENAPI_ENDPOINT_PARAMS) diff --git a/pinecone/data/index_asyncio_interface.py b/pinecone/data/index_asyncio_interface.py deleted file mode 100644 index a2647d0f8..000000000 --- a/pinecone/data/index_asyncio_interface.py +++ /dev/null @@ -1,807 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Union, List, Optional, Dict, Any - -from pinecone.core.openapi.db_data.models import ( - FetchResponse, - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, - UpsertResponse, - Vector, - ListResponse, - SparseValues, - SearchRecordsResponse, -) -from .query_results_aggregator import QueryNamespacesResults -from .types import ( - VectorTypedDict, - SparseVectorTypedDict, - VectorMetadataTypedDict, - FilterTypedDict, - VectorTuple, - VectorTupleWithMetadata, - SearchQueryTypedDict, - SearchRerankTypedDict, -) -from .dataclasses import SearchQuery, SearchRerank - - -class IndexAsyncioInterface(ABC): - @abstractmethod - async def upsert( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str] = None, - batch_size: Optional[int] = None, - show_progress: bool = True, - **kwargs, - ) -> UpsertResponse: - """ - Args: - vectors (Union[List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict]]): A list of vectors to upsert. - namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - batch_size (int): The number of vectors to upsert in each batch. - If not specified, all vectors will be upserted in a single batch. [optional] - show_progress (bool): Whether to show a progress bar using tqdm. - Applied only if batch_size is provided. Default is True. - - Returns: - `UpsertResponse`, includes the number of vectors upserted. - - - 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. - - To upsert in parallel follow: https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel - - ## Upserting dense vectors - - **Note:** the dimension of each dense vector must match the dimension of the index. - - A vector can be represented in a variety of ways. - - ```python - import asyncio - from pinecone import Pinecone, Vector - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # A Vector object - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - Vector(id='id1', values=[0.1, 0.2, 0.3, 0.4], metadata={'metadata_key': 'metadata_value'}), - ] - ) - - # A vector tuple - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - ('id1', [0.1, 0.2, 0.3, 0.4]), - ] - ) - - # A vector tuple with metadata - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - ('id1', [0.1, 0.2, 0.3, 0.4], {'metadata_key': 'metadata_value'}), - ] - ) - - # A vector dictionary - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - {"id": 1, "values": [0.1, 0.2, 0.3, 0.4], "metadata": {"metadata_key": "metadata_value"}}, - ] - - asyncio.run(main()) - ``` - - ## Upserting sparse vectors - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # A Vector object - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - Vector(id='id1', sparse_values=SparseValues(indices=[1, 2], values=[0.2, 0.4])), - ] - ) - - # A dictionary - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - {"id": 1, "sparse_values": {"indices": [1, 2], "values": [0.2, 0.4]}}, - ] - ) - - asyncio.run(main()) - ``` - - ## Batch upsert - - If you have a large number of vectors, you can upsert them in batches. - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - - await idx.upsert( - namespace = 'my-namespace', - vectors = [ - {'id': 'id1', 'values': [0.1, 0.2, 0.3, 0.4]}, - {'id': 'id2', 'values': [0.2, 0.3, 0.4, 0.5]}, - {'id': 'id3', 'values': [0.3, 0.4, 0.5, 0.6]}, - {'id': 'id4', 'values': [0.4, 0.5, 0.6, 0.7]}, - {'id': 'id5', 'values': [0.5, 0.6, 0.7, 0.8]}, - # More vectors here - ], - batch_size = 50 - ) - - asyncio.run(main()) - ``` - - ## Visual progress bar with tqdm - - To see a progress bar when upserting in batches, you will need to separately install the `tqdm` package. - If `tqdm` is present, the client will detect and use it to display progress when `show_progress=True`. - """ - pass - - @abstractmethod - async def upsert_from_dataframe( - self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True - ): - """This method has not been implemented yet for the IndexAsyncio class.""" - pass - - @abstractmethod - async def delete( - self, - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - **kwargs, - ) -> Dict[str, Any]: - """ - Args: - ids (List[str]): Vector ids to delete [optional] - delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] - Default is False. - namespace (str): The namespace to delete vectors from [optional] - If not specified, the default namespace is used. - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - 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] - - - The Delete operation deletes vectors from the index, from a single namespace. - - No error is raised if the vector id does not exist. - - Note: For any delete call, if namespace is not specified, the default namespace `""` is used. - Since the delete operation does not error when ids are not present, this means you may not receive - an error if you delete from the wrong namespace. - - Delete can occur in the following mutual exclusive ways: - 1. Delete by ids from a single namespace - 2. Delete all vectors from a single namespace by setting delete_all to True - 3. Delete all vectors from a single namespace by specifying a metadata filter - (note that for this option delete all must be set to False) - - API reference: https://docs.pinecone.io/reference/delete_post - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # Delete specific ids - await idx.delete( - ids=['id1', 'id2'], - namespace='my_namespace' - ) - - # Delete everything in a namespace - await idx.delete( - delete_all=True, - namespace='my_namespace' - ) - - # Delete by metadata filter - await idx.delete( - filter={'key': 'value'}, - namespace='my_namespace' - ) - - asyncio.run(main()) - ``` - - Returns: An empty dictionary if the delete operation was successful. - """ - pass - - @abstractmethod - async def fetch( - self, ids: List[str], namespace: Optional[str] = None, **kwargs - ) -> FetchResponse: - """ - The fetch operation looks up and returns vectors, by ID, from a single namespace. - The returned vectors include the vector data and/or metadata. - - API reference: https://docs.pinecone.io/reference/fetch - - ``` - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # Fetch specific ids in namespace - fetched = await idx.fetch( - ids=['id1', 'id2'], - namespace='my_namespace' - ) - for vec_id in fetched.vectors: - vector = fetched.vectors[vec_id] - print(vector.id) - print(vector.metadata) - print(vector.values) - - asyncio.run(main()) - ``` - - Args: - ids (List[str]): The vector IDs to fetch. - namespace (str): The namespace to fetch vectors from. - If not specified, the default namespace is used. [optional] - - Returns: FetchResponse object which contains the list of Vector objects, and namespace name. - """ - pass - - @abstractmethod - async def query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryResponse: - """ - 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. - - API reference: https://docs.pinecone.io/reference/query - - ## Querying with dense vectors - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - query_embedding = [0.1, 0.2, 0.3, ...] # An embedding that matches the index dimension - - # Query by vector values - results = await idx.query( - vector=query_embedding, - top_k=10, - filter={'genre': {"$eq": "drama"}}, # Optionally filter by metadata - namespace='my_namespace', - include_values=False, - include_metadata=True - ) - - # Query using vector id (the values from this stored vector will be used to query) - results = await idx.query( - id='1', - top_k=10, - filter={"year": {"$gt": 2000}}, - namespace='my_namespace', - ) - - asyncio.run(main()) - ``` - - ## Query with sparse vectors - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - query_embedding = [0.1, 0.2, 0.3, ...] # An embedding that matches the index dimension - - # Query by vector values - results = await idx.query( - vector=query_embedding, - top_k=10, - filter={'genre': {"$eq": "drama"}}, # Optionally filter by metadata - namespace='my_namespace', - include_values=False, - include_metadata=True - ) - - # Query using vector id (the values from this stored vector will be used to query) - results = await idx.query( - id='1', - top_k=10, - filter={"year": {"$gt": 2000}}, - namespace='my_namespace', - ) - - asyncio.run(main()) - ``` - - Examples: - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') - >>> index.query(id='id1', top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) - >>> index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) - >>> index.query(vector=[1, 2, 3], sparse_vector={'indices': [1, 2], 'values': [0.2, 0.4]}, - >>> top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], sparse_vector=SparseValues([1, 2], [0.2, 0.4]), - >>> top_k=10, namespace='my_namespace') - - 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 - `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 - `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] - filter (Dict[str, Union[str, float, int, bool, List, dict]): - The filter to apply. You can use vector metadata to limit your search. - See https://www.pinecone.io/docs/metadata-filtering/.. [optional] - include_values (bool): Indicates whether vector values are included in the response. - If omitted the server will use the default value of False [optional] - include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. - If omitted the server will use the default value of False [optional] - sparse_vector: (Union[SparseValues, Dict[str, Union[List[float], List[int]]]]): sparse values of the query vector. - Expected to be either a SparseValues object or a dict of the form: - {'indices': List[int], 'values': List[float]}, where the lists each have the same length. - - Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, - and namespace name. - """ - pass - - @abstractmethod - async def query_namespaces( - self, - namespaces: List[str], - top_k: Optional[int] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - vector: Optional[List[float]] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryNamespacesResults: - """The query_namespaces() method is used to make a query to multiple namespaces in parallel and combine the results into one result set. - - Args: - vector (List[float]): The query vector, must be the same length as the dimension of the index being queried. - namespaces (List[str]): The list of namespaces to query. - top_k (Optional[int], optional): The number of results you would like to request from each namespace. Defaults to 10. - filter (Optional[Dict[str, Union[str, float, int, bool, List, dict]]], optional): Pass an optional filter to filter results based on metadata. Defaults to None. - include_values (Optional[bool], optional): Boolean field indicating whether vector values should be included with results. Defaults to None. - include_metadata (Optional[bool], optional): Boolean field indicating whether vector metadata should be included with results. Defaults to None. - sparse_vector (Optional[ Union[SparseValues, Dict[str, Union[List[float], List[int]]]] ], optional): If you are working with a dotproduct index, you can pass a sparse vector as part of your hybrid search. Defaults to None. - - Returns: - QueryNamespacesResults: A QueryNamespacesResults object containing the combined results from all namespaces, as well as the combined usage cost in read units. - - Examples: - - ```python - import asyncio - from pinecone import Pinecone - - async def main(): - pc = Pinecone(api_key="your-api-key") - idx = pc.IndexAsyncio( - host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io", - ) - - query_vec = [0.1, 0.2, 0.3] # An embedding that matches the index dimension - combined_results = await idx.query_namespaces( - vector=query_vec, - namespaces=['ns1', 'ns2', 'ns3', 'ns4'], - top_k=10, - filter={'genre': {"$eq": "drama"}}, - include_values=True, - include_metadata=True - ) - for vec in combined_results.matches: - print(vec.id, vec.score) - print(combined_results.usage) - - await idx.close() - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def update( - self, - id: str, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Dict[str, Any]: - """ - The Update operation updates vector in a namespace. - - Args: - id (str): Vector's unique id. - values (List[float]): vector values to set. [optional] - set_metadata (Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]]): - metadata to set for vector. [optional] - namespace (str): Namespace name where to update the vector.. [optional] - sparse_values: (Dict[str, Union[List[float], List[int]]]): sparse values to update for the 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. - - 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. - - API reference: https://docs.pinecone.io/reference/update - - Examples: - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # Update vector values - await idx.update( - id='id1', - values=[0.1, 0.2, 0.3, ...], - namespace='my_namespace' - ) - - # Update metadata - await idx.update( - id='id1', - set_metadata={'key': 'value'}, - namespace='my_namespace' - ) - - # Update sparse values - await idx.update( - id='id1', - sparse_values={'indices': [1, 2], 'values': [0.2, 0.4]}, - namespace='my_namespace' - ) - - # Update sparse values with SparseValues object - await idx.update( - id='id1', - sparse_values=SparseValues(indices=[234781, 5432], values=[0.2, 0.4]), - namespace='my_namespace' - ) - - asyncio.run(main()) - ``` - - """ - pass - - @abstractmethod - async def describe_index_stats( - self, filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsResponse: - """ - The DescribeIndexStats operation returns statistics about the index's contents. - For example: The vector count per namespace and the number of dimensions. - - API reference: https://docs.pinecone.io/reference/describe_index_stats_post - - Args: - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - 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] - - Returns: DescribeIndexStatsResponse object which contains stats about the index. - - ```python - import asyncio - from pinecone import Pinecone, Vector, SparseValues - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - print(await idx.describe_index_stats()) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def list_paginated( - self, - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> ListResponse: - """ - The list_paginated operation finds vectors based on an id prefix within a single namespace. - It returns matching ids in a paginated form, with a pagination token to fetch the next page of results. - This id list can then be passed to fetch or delete operations, depending on your use case. - - Consider using the `list` method to avoid having to handle pagination tokens manually. - - Examples: - >>> results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace') - >>> [v.id for v in results.vectors] - ['99', '990', '991', '992', '993'] - >>> results.pagination.next - eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9 - >>> next_results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace', pagination_token=results.pagination.next) - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - - Returns: ListResponse object which contains the list of ids, the namespace name, pagination information, and usage showing the number of read_units consumed. - """ - pass - - @abstractmethod - async def list(self, **kwargs): - """ - The list operation accepts all of the same arguments as list_paginated, and returns a generator that yields - a list of the matching vector ids in each page of results. It automatically handles pagination tokens on your - behalf. - - Examples: - >>> for ids in index.list(prefix='99', limit=5, namespace='my_namespace'): - >>> print(ids) - ['99', '990', '991', '992', '993'] - ['994', '995', '996', '997', '998'] - ['999'] - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - """ - pass - - @abstractmethod - async def upsert_records(self, namespace: str, records: List[Dict]): - """ - :param namespace: The namespace of the index to upsert records to. - :type namespace: str, required - :param records: The records to upsert into the index. - :type records: List[Dict], required - - Upsert records to a namespace. A record is a dictionary that contains eitiher an `id` or `_id` - field along with other fields that will be stored as metadata. The `id` or `_id` field is used - as the unique identifier for the record. At least one field in the record should correspond to - a field mapping in the index's embed configuration. - - When records are upserted, Pinecone converts mapped fields into embeddings and upserts them into - the specified namespacce of the index. - - ```python - import asyncio - from pinecone import ( - Pinecone, - CloudProvider, - AwsRegion, - EmbedModel - IndexEmbed - ) - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # upsert records - await idx.upsert_records( - namespace="my-namespace", - records=[ - { - "_id": "test1", - "my_text_field": "Apple is a popular fruit known for its sweetness and crisp texture.", - }, - { - "_id": "test2", - "my_text_field": "The tech company Apple is known for its innovative products like the iPhone.", - }, - { - "_id": "test3", - "my_text_field": "Many people enjoy eating apples as a healthy snack.", - }, - { - "_id": "test4", - "my_text_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - }, - { - "_id": "test5", - "my_text_field": "An apple a day keeps the doctor away, as the saying goes.", - }, - { - "_id": "test6", - "my_text_field": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.", - }, - ], - ) - - from pinecone import SearchQuery, SearchRerank, RerankModel - - # search for similar records - response = await idx.search_records( - namespace="my-namespace", - query=SearchQuery( - inputs={ - "text": "Apple corporation", - }, - top_k=3, - ), - rerank=SearchRerank( - model=RerankModel.Bge_Reranker_V2_M3, - rank_fields=["my_text_field"], - top_n=3, - ), - ) - - asyncio.run(main()) - ``` - """ - pass - - @abstractmethod - async def search( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - """ - :param namespace: The namespace in the index to search. - :type namespace: str, required - :param query: The SearchQuery to use for the search. - :type query: Union[Dict, SearchQuery], required - :param rerank: The SearchRerank to use with the search request. - :type rerank: Union[Dict, SearchRerank], optional - :return: The records that match the search. - - Search for records. - - This operation converts a query to a vector embedding and then searches a namespace. You - can optionally provide a reranking operation as part of the search. - - ```python - import asyncio - from pinecone import ( - Pinecone, - CloudProvider, - AwsRegion, - EmbedModel - IndexEmbed - ) - - async def main(): - pc = Pinecone() - async with pc.IndexAsyncio(host="example-dojoi3u.svc.aped-4627-b74a.pinecone.io") as idx: - # upsert records - await idx.upsert_records( - namespace="my-namespace", - records=[ - { - "_id": "test1", - "my_text_field": "Apple is a popular fruit known for its sweetness and crisp texture.", - }, - { - "_id": "test2", - "my_text_field": "The tech company Apple is known for its innovative products like the iPhone.", - }, - { - "_id": "test3", - "my_text_field": "Many people enjoy eating apples as a healthy snack.", - }, - { - "_id": "test4", - "my_text_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - }, - { - "_id": "test5", - "my_text_field": "An apple a day keeps the doctor away, as the saying goes.", - }, - { - "_id": "test6", - "my_text_field": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.", - }, - ], - ) - - from pinecone import SearchQuery, SearchRerank, RerankModel - - # search for similar records - response = await idx.search_records( - namespace="my-namespace", - query=SearchQuery( - inputs={ - "text": "Apple corporation", - }, - top_k=3, - ), - rerank=SearchRerank( - model=RerankModel.Bge_Reranker_V2_M3, - rank_fields=["my_text_field"], - top_n=3, - ), - ) - - asyncio.run(main()) - ``` - - """ - pass - - @abstractmethod - async def search_records( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - """Alias of the search() method.""" - pass diff --git a/pinecone/data/interfaces.py b/pinecone/data/interfaces.py deleted file mode 100644 index cbcc84b5d..000000000 --- a/pinecone/data/interfaces.py +++ /dev/null @@ -1,681 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Union, List, Optional, Dict, Any - -from pinecone.core.openapi.db_data.models import ( - FetchResponse, - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, - UpsertResponse, - Vector, - ListResponse, - SparseValues, - SearchRecordsResponse, -) -from .query_results_aggregator import QueryNamespacesResults -from multiprocessing.pool import ApplyResult -from .types import ( - VectorTypedDict, - SparseVectorTypedDict, - VectorMetadataTypedDict, - FilterTypedDict, - VectorTuple, - VectorTupleWithMetadata, - SearchQueryTypedDict, - SearchRerankTypedDict, -) -from .dataclasses import SearchQuery, SearchRerank - - -class IndexInterface(ABC): - @abstractmethod - def upsert( - self, - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str] = None, - batch_size: Optional[int] = None, - show_progress: bool = True, - **kwargs, - ) -> UpsertResponse: - """ - Args: - vectors (Union[List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict]]): A list of vectors to upsert. - namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - batch_size (int): The number of vectors to upsert in each batch. - If not specified, all vectors will be upserted in a single batch. [optional] - show_progress (bool): Whether to show a progress bar using tqdm. - Applied only if batch_size is provided. Default is True. - - Returns: - `UpsertResponse`, includes the number of vectors upserted. - - - 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. - - To upsert in parallel follow: https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel - - ## Upserting dense vectors - - **Note:** the dimension of each dense vector must match the dimension of the index. - - A vector can be represented in a variety of ways. - - ```python - from pinecone import Pinecone, Vector - - pc = Pinecone() - idx = pc.Index("index-name") - - # A Vector object - idx.upsert( - namespace = 'my-namespace', - vectors = [ - Vector(id='id1', values=[0.1, 0.2, 0.3, 0.4], metadata={'metadata_key': 'metadata_value'}), - ] - ) - - # A vector tuple - idx.upsert( - namespace = 'my-namespace', - vectors = [ - ('id1', [0.1, 0.2, 0.3, 0.4]), - ] - ) - - # A vector tuple with metadata - idx.upsert( - namespace = 'my-namespace', - vectors = [ - ('id1', [0.1, 0.2, 0.3, 0.4], {'metadata_key': 'metadata_value'}), - ] - ) - - # A vector dictionary - idx.upsert( - namespace = 'my-namespace', - vectors = [ - {"id": 1, "values": [0.1, 0.2, 0.3, 0.4], "metadata": {"metadata_key": "metadata_value"}}, - ] - ``` - - ## Upserting sparse vectors - - ```python - from pinecone import Pinecone, Vector, SparseValues - - pc = Pinecone() - idx = pc.Index("index-name") - - # A Vector object - idx.upsert( - namespace = 'my-namespace', - vectors = [ - Vector(id='id1', sparse_values=SparseValues(indices=[1, 2], values=[0.2, 0.4])), - ] - ) - - # A dictionary - idx.upsert( - namespace = 'my-namespace', - vectors = [ - {"id": 1, "sparse_values": {"indices": [1, 2], "values": [0.2, 0.4]}}, - ] - ) - ``` - - ## Batch upsert - - If you have a large number of vectors, you can upsert them in batches. - - ```python - from pinecone import Pinecone, Vector - - pc = Pinecone() - idx = pc.Index("index-name") - - idx.upsert( - namespace = 'my-namespace', - vectors = [ - {'id': 'id1', 'values': [0.1, 0.2, 0.3, 0.4]}, - {'id': 'id2', 'values': [0.2, 0.3, 0.4, 0.5]}, - {'id': 'id3', 'values': [0.3, 0.4, 0.5, 0.6]}, - {'id': 'id4', 'values': [0.4, 0.5, 0.6, 0.7]}, - {'id': 'id5', 'values': [0.5, 0.6, 0.7, 0.8]}, - # More vectors here - ], - batch_size = 50 - ) - ``` - - ## Visual progress bar with tqdm - - To see a progress bar when upserting in batches, you will need to separately install the `tqdm` package. - If `tqdm` is present, the client will detect and use it to display progress when `show_progress=True`. - """ - pass - - @abstractmethod - def upsert_from_dataframe( - self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True - ): - """Upserts a dataframe into the index. - - Args: - df: A pandas dataframe with the following columns: id, values, sparse_values, and metadata. - namespace: The namespace to upsert into. - batch_size: The number of rows to upsert in a single batch. - show_progress: Whether to show a progress bar. - """ - pass - - @abstractmethod - def upsert_records(self, namespace: str, records: List[Dict]): - """ - :param namespace: The namespace of the index to upsert records to. - :type namespace: str, required - :param records: The records to upsert into the index. - :type records: List[Dict], required - - Upsert records to a namespace. A record is a dictionary that contains eitiher an `id` or `_id` - field along with other fields that will be stored as metadata. The `id` or `_id` field is used - as the unique identifier for the record. At least one field in the record should correspond to - a field mapping in the index's embed configuration. - - When records are upserted, Pinecone converts mapped fields into embeddings and upserts them into - the specified namespacce of the index. - - ```python - from pinecone import ( - Pinecone, - CloudProvider, - AwsRegion, - EmbedModel - IndexEmbed - ) - - pc = Pinecone(api_key="<>") - - # Create an index for your embedding model - index_model = pc.create_index_for_model( - name="my-model-index", - cloud=CloudProvider.AWS, - region=AwsRegion.US_WEST_2, - embed=IndexEmbed( - model=EmbedModel.Multilingual_E5_Large, - field_map={"text": "my_text_field"} - ) - ) - - # Instantiate the index client - idx = pc.Index(host=index_model.host) - - # upsert records - idx.upsert_records( - namespace="my-namespace", - records=[ - { - "_id": "test1", - "my_text_field": "Apple is a popular fruit known for its sweetness and crisp texture.", - }, - { - "_id": "test2", - "my_text_field": "The tech company Apple is known for its innovative products like the iPhone.", - }, - { - "_id": "test3", - "my_text_field": "Many people enjoy eating apples as a healthy snack.", - }, - { - "_id": "test4", - "my_text_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - }, - { - "_id": "test5", - "my_text_field": "An apple a day keeps the doctor away, as the saying goes.", - }, - { - "_id": "test6", - "my_text_field": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.", - }, - ], - ) - - from pinecone import SearchQuery, SearchRerank, RerankModel - - # search for similar records - response = idx.search_records( - namespace="my-namespace", - query=SearchQuery( - inputs={ - "text": "Apple corporation", - }, - top_k=3, - ), - rerank=SearchRerank( - model=RerankModel.Bge_Reranker_V2_M3, - rank_fields=["my_text_field"], - top_n=3, - ), - ) - ``` - """ - pass - - @abstractmethod - def search( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - """ - :param namespace: The namespace in the index to search. - :type namespace: str, required - :param query: The SearchQuery to use for the search. - :type query: Union[Dict, SearchQuery], required - :param rerank: The SearchRerank to use with the search request. - :type rerank: Union[Dict, SearchRerank], optional - :return: The records that match the search. - - Search for records. - - This operation converts a query to a vector embedding and then searches a namespace. You - can optionally provide a reranking operation as part of the search. - - ```python - from pinecone import ( - Pinecone, - CloudProvider, - AwsRegion, - EmbedModel - IndexEmbed - ) - - pc = Pinecone(api_key="<>") - - # Create an index for your embedding model - index_model = pc.create_index_for_model( - name="my-model-index", - cloud=CloudProvider.AWS, - region=AwsRegion.US_WEST_2, - embed=IndexEmbed( - model=EmbedModel.Multilingual_E5_Large, - field_map={"text": "my_text_field"} - ) - ) - - # Instantiate the index client - idx = pc.Index(host=index_model.host) - - # upsert records - idx.upsert_records( - namespace="my-namespace", - records=[ - { - "_id": "test1", - "my_text_field": "Apple is a popular fruit known for its sweetness and crisp texture.", - }, - { - "_id": "test2", - "my_text_field": "The tech company Apple is known for its innovative products like the iPhone.", - }, - { - "_id": "test3", - "my_text_field": "Many people enjoy eating apples as a healthy snack.", - }, - { - "_id": "test4", - "my_text_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.", - }, - { - "_id": "test5", - "my_text_field": "An apple a day keeps the doctor away, as the saying goes.", - }, - { - "_id": "test6", - "my_text_field": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.", - }, - ], - ) - - from pinecone import SearchQuery, SearchRerank, RerankModel - - # search for similar records - response = idx.search_records( - namespace="my-namespace", - query=SearchQuery( - inputs={ - "text": "Apple corporation", - }, - top_k=3, - ), - rerank=SearchRerank( - model=RerankModel.Bge_Reranker_V2_M3, - rank_fields=["my_text_field"], - top_n=3, - ), - ) - ``` - """ - pass - - @abstractmethod - def search_records( - self, - namespace: str, - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsResponse: - """Alias of the search() method.""" - pass - - @abstractmethod - def delete( - self, - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - **kwargs, - ) -> Dict[str, Any]: - """ - Args: - ids (List[str]): Vector ids to delete [optional] - delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] - Default is False. - namespace (str): The namespace to delete vectors from [optional] - If not specified, the default namespace is used. - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - 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] - - - The Delete operation deletes vectors from the index, from a single namespace. - - No error is raised if the vector id does not exist. - - Note: For any delete call, if namespace is not specified, the default namespace `""` is used. - Since the delete operation does not error when ids are not present, this means you may not receive - an error if you delete from the wrong namespace. - - Delete can occur in the following mutual exclusive ways: - 1. Delete by ids from a single namespace - 2. Delete all vectors from a single namespace by setting delete_all to True - 3. Delete all vectors from a single namespace by specifying a metadata filter - (note that for this option delete all must be set to False) - - API reference: https://docs.pinecone.io/reference/delete_post - - Examples: - >>> index.delete(ids=['id1', 'id2'], namespace='my_namespace') - >>> index.delete(delete_all=True, namespace='my_namespace') - >>> index.delete(filter={'key': 'value'}, namespace='my_namespace') - - - Returns: An empty dictionary if the delete operation was successful. - """ - pass - - @abstractmethod - def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: - """ - The fetch operation looks up and returns vectors, by ID, from a single namespace. - The returned vectors include the vector data and/or metadata. - - API reference: https://docs.pinecone.io/reference/fetch - - Examples: - >>> index.fetch(ids=['id1', 'id2'], namespace='my_namespace') - >>> index.fetch(ids=['id1', 'id2']) - - Args: - ids (List[str]): The vector IDs to fetch. - namespace (str): The namespace to fetch vectors from. - If not specified, the default namespace is used. [optional] - - Returns: FetchResponse object which contains the list of Vector objects, and namespace name. - """ - pass - - @abstractmethod - def query( - self, - *args, - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Union[QueryResponse, ApplyResult]: - """ - 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. - - API reference: https://docs.pinecone.io/reference/query - - Examples: - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') - >>> index.query(id='id1', top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) - >>> index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) - >>> index.query(vector=[1, 2, 3], sparse_vector={'indices': [1, 2], 'values': [0.2, 0.4]}, - >>> top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], sparse_vector=SparseValues([1, 2], [0.2, 0.4]), - >>> top_k=10, namespace='my_namespace') - - 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 - `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 - `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 query vectors from. - If not specified, the default namespace is used. [optional] - filter (Dict[str, Union[str, float, int, bool, List, dict]): - The filter to apply. You can use vector metadata to limit your search. - See https://www.pinecone.io/docs/metadata-filtering/.. [optional] - include_values (bool): Indicates whether vector values are included in the response. - If omitted the server will use the default value of False [optional] - include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. - If omitted the server will use the default value of False [optional] - sparse_vector: (Union[SparseValues, Dict[str, Union[List[float], List[int]]]]): sparse values of the query vector. - Expected to be either a SparseValues object or a dict of the form: - {'indices': List[int], 'values': List[float]}, where the lists each have the same length. - - Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, - and namespace name. - """ - pass - - @abstractmethod - def query_namespaces( - self, - vector: List[float], - namespaces: List[str], - top_k: Optional[int] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryNamespacesResults: - """The query_namespaces() method is used to make a query to multiple namespaces in parallel and combine the results into one result set. - - Since several asynchronous calls are made on your behalf when calling this method, you will need to tune the pool_threads and connection_pool_maxsize parameter of the Index constructor to suite your workload. - - Examples: - - ```python - from pinecone import Pinecone - - pc = Pinecone(api_key="your-api-key") - index = pc.Index( - host="index-name", - pool_threads=32, - connection_pool_maxsize=32 - ) - - query_vec = [0.1, 0.2, 0.3] # An embedding that matches the index dimension - combined_results = index.query_namespaces( - vector=query_vec, - namespaces=['ns1', 'ns2', 'ns3', 'ns4'], - metric="cosine", - top_k=10, - filter={'genre': {"$eq": "drama"}}, - include_values=True, - include_metadata=True - ) - for vec in combined_results.matches: - print(vec.id, vec.score) - print(combined_results.usage) - ``` - - Args: - vector (List[float]): The query vector, must be the same length as the dimension of the index being queried. - namespaces (List[str]): The list of namespaces to query. - top_k (Optional[int], optional): The number of results you would like to request from each namespace. Defaults to 10. - metric (str): Must be one of 'cosine', 'euclidean', 'dotproduct'. This is needed in order to merge results across namespaces, since the interpretation of score depends on the index metric type. - filter (Optional[Dict[str, Union[str, float, int, bool, List, dict]]], optional): Pass an optional filter to filter results based on metadata. Defaults to None. - include_values (Optional[bool], optional): Boolean field indicating whether vector values should be included with results. Defaults to None. - include_metadata (Optional[bool], optional): Boolean field indicating whether vector metadata should be included with results. Defaults to None. - sparse_vector (Optional[ Union[SparseValues, Dict[str, Union[List[float], List[int]]]] ], optional): If you are working with a dotproduct index, you can pass a sparse vector as part of your hybrid search. Defaults to None. - - Returns: - QueryNamespacesResults: A QueryNamespacesResults object containing the combined results from all namespaces, as well as the combined usage cost in read units. - """ - pass - - @abstractmethod - def update( - self, - id: str, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Dict[str, Any]: - """ - 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. - - API reference: https://docs.pinecone.io/reference/update - - Examples: - >>> index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') - >>> index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace') - >>> index.update(id='id1', values=[1, 2, 3], sparse_values={'indices': [1, 2], 'values': [0.2, 0.4]}, - >>> namespace='my_namespace') - >>> index.update(id='id1', values=[1, 2, 3], sparse_values=SparseValues(indices=[1, 2], values=[0.2, 0.4]), - >>> namespace='my_namespace') - - Args: - id (str): Vector's unique id. - values (List[float]): vector values to set. [optional] - set_metadata (Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]]): - metadata to set for vector. [optional] - namespace (str): Namespace name where to update the vector.. [optional] - sparse_values: (Dict[str, Union[List[float], List[int]]]): sparse values to update for the 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. - - - Returns: An empty dictionary if the update was successful. - """ - pass - - @abstractmethod - def describe_index_stats( - self, filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsResponse: - """ - The DescribeIndexStats operation returns statistics about the index's contents. - For example: The vector count per namespace and the number of dimensions. - - API reference: https://docs.pinecone.io/reference/describe_index_stats_post - - Examples: - >>> index.describe_index_stats() - >>> index.describe_index_stats(filter={'key': 'value'}) - - Args: - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - 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] - - Returns: DescribeIndexStatsResponse object which contains stats about the index. - """ - pass - - @abstractmethod - def list_paginated( - self, - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> ListResponse: - """ - The list_paginated operation finds vectors based on an id prefix within a single namespace. - It returns matching ids in a paginated form, with a pagination token to fetch the next page of results. - This id list can then be passed to fetch or delete operations, depending on your use case. - - Consider using the `list` method to avoid having to handle pagination tokens manually. - - Examples: - >>> results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace') - >>> [v.id for v in results.vectors] - ['99', '990', '991', '992', '993'] - >>> results.pagination.next - eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9 - >>> next_results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace', pagination_token=results.pagination.next) - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - - Returns: ListResponse object which contains the list of ids, the namespace name, pagination information, and usage showing the number of read_units consumed. - """ - pass - - @abstractmethod - def list(self, **kwargs): - """ - The list operation accepts all of the same arguments as list_paginated, and returns a generator that yields - a list of the matching vector ids in each page of results. It automatically handles pagination tokens on your - behalf. - - Examples: - >>> for ids in index.list(prefix='99', limit=5, namespace='my_namespace'): - >>> print(ids) - ['99', '990', '991', '992', '993'] - ['994', '995', '996', '997', '998'] - ['999'] - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - """ - pass diff --git a/pinecone/data/query_results_aggregator.py b/pinecone/data/query_results_aggregator.py deleted file mode 100644 index 9bb207bda..000000000 --- a/pinecone/data/query_results_aggregator.py +++ /dev/null @@ -1,177 +0,0 @@ -from typing import List, Tuple, Optional, Any, Dict, Literal -import json -import heapq -from pinecone.core.openapi.db_data.models import Usage -from pinecone.core.openapi.db_data.models import QueryResponse as OpenAPIQueryResponse - -from dataclasses import dataclass, asdict - - -@dataclass -class ScoredVectorWithNamespace: - namespace: str - score: float - id: str - values: List[float] - sparse_values: dict - metadata: dict - - def __init__(self, aggregate_results_heap_tuple: Tuple[float, int, object, str]) -> None: - json_vector = aggregate_results_heap_tuple[2] - self.namespace = aggregate_results_heap_tuple[3] - self.id = json_vector.get("id") # type: ignore - self.score = json_vector.get("score") # type: ignore - self.values = json_vector.get("values") # type: ignore - self.sparse_values = json_vector.get("sparse_values", None) # type: ignore - self.metadata = json_vector.get("metadata", None) # type: ignore - - def __getitem__(self, key): - if hasattr(self, key): - return getattr(self, key) - else: - raise KeyError(f"'{key}' not found in ScoredVectorWithNamespace") - - def get(self, key, default=None): - return getattr(self, key, default) - - def __repr__(self): - return json.dumps(self._truncate(asdict(self)), indent=4) - - def __json__(self): - return self._truncate(asdict(self)) - - def _truncate(self, obj, max_items=2): - """ - Recursively traverse and truncate lists that exceed max_items length. - Only display the "... X more" message if at least 2 elements are hidden. - """ - if obj is None: - return None # Skip None values - elif isinstance(obj, list): - filtered_list = [self._truncate(i, max_items) for i in obj if i is not None] - if len(filtered_list) > max_items: - # Show the truncation message only if more than 1 item is hidden - remaining_items = len(filtered_list) - max_items - if remaining_items > 1: - return filtered_list[:max_items] + [f"... {remaining_items} more"] - else: - # If only 1 item remains, show it - return filtered_list - return filtered_list - elif isinstance(obj, dict): - # Recursively process dictionaries, omitting None values - return {k: self._truncate(v, max_items) for k, v in obj.items() if v is not None} - return obj - - -@dataclass -class QueryNamespacesResults: - usage: Usage - matches: List[ScoredVectorWithNamespace] - - def __getitem__(self, key): - if hasattr(self, key): - return getattr(self, key) - else: - raise KeyError(f"'{key}' not found in QueryNamespacesResults") - - def get(self, key, default=None): - return getattr(self, key, default) - - def __repr__(self): - return json.dumps( - { - "usage": self.usage.to_dict(), - "matches": [match.__json__() for match in self.matches], - }, - indent=4, - ) - - -class QueryResultsAggregatorInvalidTopKError(Exception): - def __init__(self, top_k: int) -> None: - super().__init__(f"Invalid top_k value {top_k}. top_k must be at least 1.") - - -class QueryResultsAggregator: - def __init__(self, top_k: int, metric: Literal["cosine", "euclidean", "dotproduct"]) -> None: - if top_k < 1: - raise QueryResultsAggregatorInvalidTopKError(top_k) - - if metric in ["dotproduct", "cosine"]: - self.is_bigger_better = True - elif metric in ["euclidean"]: - self.is_bigger_better = False - else: - raise ValueError( - f"Cannot merge results for unknown similarity metric {metric}. Supported metrics are 'dotproduct', 'cosine', and 'euclidean'." - ) - - self.top_k = top_k - self.usage_read_units = 0 - self.heap: List[Tuple[float, int, object, str]] = [] - self.insertion_counter = 0 - self.read = False - self.final_results: Optional[QueryNamespacesResults] = None - - def _bigger_better_heap_item(self, match, ns): - # This 4-tuple is used to ensure that the heap is sorted by score followed by - # insertion order. The insertion order is used to break any ties in the score. - return (match.get("score"), -self.insertion_counter, match, ns) - - def _smaller_better_heap_item(self, match, ns): - return (-match.get("score"), -self.insertion_counter, match, ns) - - def _process_matches(self, matches, ns, heap_item_fn): - for match in matches: - self.insertion_counter += 1 - if len(self.heap) < self.top_k: - heapq.heappush(self.heap, heap_item_fn(match, ns)) - else: - # Assume we have dotproduct scores sorted in descending order - if self.is_bigger_better and match["score"] < self.heap[0][0]: - # No further matches can improve the top-K heap - break - elif not self.is_bigger_better and match["score"] > -self.heap[0][0]: - # No further matches can improve the top-K heap - break - heapq.heappushpop(self.heap, heap_item_fn(match, ns)) - - def add_results(self, results: Dict[str, Any]): - if self.read: - # This is mainly just to sanity check in test cases which get quite confusing - # if you read results twice due to the heap being emptied when constructing - # the ordered results. - raise ValueError("Results have already been read. Cannot add more results.") - - matches = results.get("matches", []) - ns: str = results.get("namespace", "") - if isinstance(results, OpenAPIQueryResponse): - self.usage_read_units += results.usage.read_units - else: - self.usage_read_units += results.get("usage", {}).get("readUnits", 0) - - if len(matches) == 0: - return - - if self.is_bigger_better: - self._process_matches(matches, ns, self._bigger_better_heap_item) - else: - self._process_matches(matches, ns, self._smaller_better_heap_item) - - def get_results(self) -> QueryNamespacesResults: - if self.read: - if self.final_results is not None: - return self.final_results - else: - # I don't think this branch can ever actually be reached, but the type checker disagrees - raise ValueError("Results have already been read. Cannot get results again.") - self.read = True - - self.final_results = QueryNamespacesResults( - usage=Usage(read_units=self.usage_read_units), - matches=[ - ScoredVectorWithNamespace(heapq.heappop(self.heap)) for _ in range(len(self.heap)) - ][::-1], - ) - return self.final_results diff --git a/pinecone/data/request_factory.py b/pinecone/data/request_factory.py deleted file mode 100644 index fded9b6ba..000000000 --- a/pinecone/data/request_factory.py +++ /dev/null @@ -1,271 +0,0 @@ -import logging -from typing import Union, List, Optional, Dict, Any, cast - -from pinecone.core.openapi.db_data.models import ( - QueryRequest, - UpsertRequest, - DeleteRequest, - UpdateRequest, - DescribeIndexStatsRequest, - SearchRecordsRequest, - SearchRecordsRequestQuery, - SearchRecordsRequestRerank, - VectorValues, - SearchRecordsVector, - UpsertRecord, -) -from ..utils import parse_non_empty_args, convert_enum_to_string -from .vector_factory import VectorFactory -from .sparse_values_factory import SparseValuesFactory -from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS -from .types import ( - VectorTypedDict, - SparseVectorTypedDict, - VectorMetadataTypedDict, - VectorTuple, - VectorTupleWithMetadata, - FilterTypedDict, - SearchQueryTypedDict, - SearchRerankTypedDict, - SearchQueryVectorTypedDict, -) - -from .dataclasses import Vector, SparseValues, SearchQuery, SearchRerank, SearchQueryVector - -logger = logging.getLogger(__name__) -""" @private """ - - -def non_openapi_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]: - return {k: v for k, v in kwargs.items() if k not in OPENAPI_ENDPOINT_PARAMS} - - -class IndexRequestFactory: - @staticmethod - def query_request( - top_k: int, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryRequest: - if vector is not None and id is not None: - raise ValueError("Cannot specify both `id` and `vector`") - - sparse_vector_normalized = SparseValuesFactory.build(sparse_vector) - args_dict = parse_non_empty_args( - [ - ("vector", vector), - ("id", id), - ("queries", None), - ("top_k", top_k), - ("namespace", namespace), - ("filter", filter), - ("include_values", include_values), - ("include_metadata", include_metadata), - ("sparse_vector", sparse_vector_normalized), - ] - ) - - return QueryRequest( - **args_dict, _check_type=kwargs.pop("_check_type", False), **non_openapi_kwargs(kwargs) - ) - - @staticmethod - def upsert_request( - vectors: Union[ - List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict] - ], - namespace: Optional[str], - _check_type: bool, - **kwargs, - ) -> UpsertRequest: - args_dict = parse_non_empty_args([("namespace", namespace)]) - - def vec_builder(v): - return VectorFactory.build(v, check_type=_check_type) - - return UpsertRequest( - vectors=list(map(vec_builder, vectors)), - **args_dict, - _check_type=_check_type, - **non_openapi_kwargs(kwargs), - ) - - @staticmethod - def delete_request( - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, - **kwargs, - ) -> DeleteRequest: - _check_type = kwargs.pop("_check_type", False) - args_dict = parse_non_empty_args( - [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter)] - ) - return DeleteRequest(**args_dict, **non_openapi_kwargs(kwargs), _check_type=_check_type) - - @staticmethod - def update_request( - id: str, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> UpdateRequest: - _check_type = kwargs.pop("_check_type", False) - sparse_values_normalized = SparseValuesFactory.build(sparse_values) - args_dict = parse_non_empty_args( - [ - ("values", values), - ("set_metadata", set_metadata), - ("namespace", namespace), - ("sparse_values", sparse_values_normalized), - ] - ) - - return UpdateRequest( - id=id, **args_dict, _check_type=_check_type, **non_openapi_kwargs(kwargs) - ) - - @staticmethod - def describe_index_stats_request( - filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsRequest: - _check_type = kwargs.pop("_check_type", False) - args_dict = parse_non_empty_args([("filter", filter)]) - - return DescribeIndexStatsRequest( - **args_dict, **non_openapi_kwargs(kwargs), _check_type=_check_type - ) - - @staticmethod - def list_paginated_args( - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> Dict[str, Any]: - return parse_non_empty_args( - [ - ("prefix", prefix), - ("limit", limit), - ("namespace", namespace), - ("pagination_token", pagination_token), - ] - ) - - @staticmethod - def search_request( - query: Union[SearchQueryTypedDict, SearchQuery], - rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None, - fields: Optional[List[str]] = ["*"], # Default to returning all fields - ) -> SearchRecordsRequest: - request_args = parse_non_empty_args( - [ - ("query", IndexRequestFactory._parse_search_query(query)), - ("fields", fields), - ("rerank", IndexRequestFactory._parse_search_rerank(rerank)), - ] - ) - - return SearchRecordsRequest(**request_args) - - @staticmethod - def _parse_search_query( - query: Union[SearchQueryTypedDict, SearchQuery], - ) -> SearchRecordsRequestQuery: - if isinstance(query, SearchQuery): - query_dict = query.as_dict() - else: - query_dict = cast(dict[str, Any], query) - - required_fields = {"top_k"} - for key in required_fields: - if query_dict.get(key, None) is None: - raise ValueError(f"Missing required field '{key}' in search query.") - - # User-provided dict could contain object that need conversion - if isinstance(query_dict.get("vector", None), SearchQueryVector): - query_dict["vector"] = query_dict["vector"].as_dict() - - srrq = SearchRecordsRequestQuery( - **{k: v for k, v in query_dict.items() if k not in {"vector"}} - ) - if query_dict.get("vector", None) is not None: - srrq.vector = IndexRequestFactory._parse_search_vector(query_dict["vector"]) - return srrq - - @staticmethod - def _parse_search_vector( - vector: Optional[Union[SearchQueryVectorTypedDict, SearchQueryVector]], - ): - if vector is None: - return None - - if isinstance(vector, SearchQueryVector): - if vector.values is None and vector.sparse_values is None: - return None - vector_dict = vector.as_dict() - else: - vector_dict = cast(dict[str, Any], vector) - if ( - vector_dict.get("values", None) is None - and vector_dict.get("sparse_values", None) is None - ): - return None - - srv = SearchRecordsVector(**{k: v for k, v in vector_dict.items() if k not in {"values"}}) - - values = vector_dict.get("values", None) - if values is not None: - srv.values = VectorValues(value=values) - - return srv - - @staticmethod - def _parse_search_rerank(rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None): - if rerank is None: - return None - - if isinstance(rerank, SearchRerank): - rerank_dict = rerank.as_dict() - else: - rerank_dict = cast(dict[str, Any], rerank) - - required_fields = {"model", "rank_fields"} - for key in required_fields: - if rerank_dict.get(key, None) is None: - raise ValueError(f"Missing required field '{key}' in rerank.") - - rerank_dict["model"] = convert_enum_to_string(rerank_dict["model"]) - - return SearchRecordsRequestRerank(**rerank_dict) - - @staticmethod - def upsert_records_args(namespace: str, records: List[Dict]): - if namespace is None: - raise ValueError("namespace is required when upserting records") - if not records or len(records) == 0: - raise ValueError("No records provided") - - records_to_upsert = [] - for record in records: - if not record.get("_id") and not record.get("id"): - raise ValueError("Each record must have an '_id' or 'id' value") - - records_to_upsert.append( - UpsertRecord( - record.get("_id", record.get("id")), - **{k: v for k, v in record.items() if k not in {"_id", "id"}}, - ) - ) - - return {"namespace": namespace, "upsert_record": records_to_upsert} diff --git a/pinecone/data/sparse_values_factory.py b/pinecone/data/sparse_values_factory.py deleted file mode 100644 index 5d07136eb..000000000 --- a/pinecone/data/sparse_values_factory.py +++ /dev/null @@ -1,59 +0,0 @@ -from collections.abc import Mapping -from typing import Union, Optional - -from ..utils import convert_to_list - -from .errors import ( - SparseValuesTypeError, - SparseValuesMissingKeysError, - SparseValuesDictionaryExpectedError, -) - -from .dataclasses import SparseValues -from .types import SparseVectorTypedDict -from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues - - -class SparseValuesFactory: - """SparseValuesFactory is used to convert various types of user input into SparseValues objects used in generated request code.""" - - @staticmethod - def build( - input: Optional[Union[SparseValues, OpenApiSparseValues, SparseVectorTypedDict]], - ) -> Optional[OpenApiSparseValues]: - if input is None: - return input - if isinstance(input, OpenApiSparseValues): - return input - if isinstance(input, SparseValues): - return OpenApiSparseValues(indices=input.indices, values=input.values) - if not isinstance(input, Mapping): - raise SparseValuesDictionaryExpectedError(input) - if not {"indices", "values"}.issubset(input): - raise SparseValuesMissingKeysError(input) - - indices = SparseValuesFactory._convert_to_list(input.get("indices"), int) - values = SparseValuesFactory._convert_to_list(input.get("values"), float) - - if len(indices) != len(values): - raise ValueError("Sparse values indices and values must have the same length") - - try: - return OpenApiSparseValues(indices=indices, values=values) - except TypeError as e: - raise SparseValuesTypeError() from e - - @staticmethod - def _convert_to_list(input, expected_type): - try: - converted = convert_to_list(input) - except TypeError as e: - raise SparseValuesTypeError() from e - - SparseValuesFactory._validate_list_items_type(converted, expected_type) - return converted - - @staticmethod - def _validate_list_items_type(input, expected_type): - if len(input) > 0 and not isinstance(input[0], expected_type): - raise SparseValuesTypeError() diff --git a/pinecone/data/types/__init__.py b/pinecone/data/types/__init__.py deleted file mode 100644 index ccc9fb50d..000000000 --- a/pinecone/data/types/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from .sparse_vector_typed_dict import SparseVectorTypedDict -from .vector_typed_dict import VectorTypedDict -from .vector_metadata_dict import VectorMetadataTypedDict -from .vector_tuple import VectorTuple, VectorTupleWithMetadata -from .query_filter import FilterTypedDict -from .search_rerank_typed_dict import SearchRerankTypedDict -from .search_query_typed_dict import SearchQueryTypedDict -from .search_query_vector_typed_dict import SearchQueryVectorTypedDict diff --git a/pinecone/data/types/query_filter.py b/pinecone/data/types/query_filter.py deleted file mode 100644 index 927382f61..000000000 --- a/pinecone/data/types/query_filter.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Literal, Dict, List, Union - -FieldValue = Union[str, int, float, bool] - -ExactMatchFilter = Dict[str, FieldValue] - -EqFilter = Dict[Literal["$eq"], FieldValue] -NeFilter = Dict[Literal["$ne"], FieldValue] - -NumericFieldValue = Union[int, float] -GtFilter = Dict[Literal["$gt"], NumericFieldValue] -GteFilter = Dict[Literal["$gte"], NumericFieldValue] -LtFilter = Dict[Literal["$lt"], NumericFieldValue] -LteFilter = Dict[Literal["$lte"], NumericFieldValue] - -InFilter = Dict[Literal["$in"], List[FieldValue]] -NinFilter = Dict[Literal["$nin"], List[FieldValue]] - - -SimpleFilter = Union[ - ExactMatchFilter, - EqFilter, - NeFilter, - GtFilter, - GteFilter, - LtFilter, - LteFilter, - InFilter, - NinFilter, -] -AndFilter = Dict[Literal["$and"], List[SimpleFilter]] - -FilterTypedDict = Union[SimpleFilter, AndFilter] diff --git a/pinecone/data/types/search_query_typed_dict.py b/pinecone/data/types/search_query_typed_dict.py deleted file mode 100644 index c21ba1202..000000000 --- a/pinecone/data/types/search_query_typed_dict.py +++ /dev/null @@ -1,36 +0,0 @@ -from typing import TypedDict, Optional, Union, Dict, Any -from .search_query_vector_typed_dict import SearchQueryVectorTypedDict - - -class SearchQueryTypedDict(TypedDict): - """ - SearchQuery represents the query when searching within a specific namespace. - """ - - inputs: Dict[str, Any] - """ - The input data to search with. - Required. - """ - - top_k: int - """ - The number of results to return with each search. - Required. - """ - - filter: Optional[Dict[str, Any]] - """ - The filter to apply to the search. - Optional. - """ - - vector: Optional[Union[SearchQueryVectorTypedDict]] - """ - The vector values to search with. If provided, it overwrites the inputs. - """ - - id: Optional[str] - """ - The unique ID of the vector to be used as a query vector. - """ diff --git a/pinecone/data/types/search_query_vector_typed_dict.py b/pinecone/data/types/search_query_vector_typed_dict.py deleted file mode 100644 index 4269b904a..000000000 --- a/pinecone/data/types/search_query_vector_typed_dict.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import TypedDict, Optional, List - - -class SearchQueryVectorTypedDict(TypedDict): - """ - SearchQueryVector represents the vector values used to query. - """ - - values: Optional[List[float]] - """ - The vector data included in the search request. - Optional. - """ - - sparse_values: Optional[List[float]] - """ - The sparse embedding values to search with. - Optional. - """ - - sparse_indices: Optional[List[int]] - """ - The sparse embedding indices to search with. - Optional. - """ diff --git a/pinecone/data/types/search_rerank_typed_dict.py b/pinecone/data/types/search_rerank_typed_dict.py deleted file mode 100644 index 89c4f8d8a..000000000 --- a/pinecone/data/types/search_rerank_typed_dict.py +++ /dev/null @@ -1,41 +0,0 @@ -from typing import TypedDict, Optional, Union, Dict, Any -from ..features.inference import RerankModel - - -class SearchRerankTypedDict(TypedDict): - # """ - # SearchRerank represents a rerank request when searching within a specific namespace. - # """ - - model: Union[str, RerankModel] - # model: str - # """ - # The name of the [reranking model](https://docs.pinecone.io/guides/inference/understanding-inference#reranking-models) to use. - # Required. - # """ - - rank_fields: list[str] - # rank_fields: List[str] - # """ - # The fields to use for reranking. - # Required. - # """ - - top_n: Optional[int] - # """ - # The number of top results to return after reranking. Defaults to top_k. - # Optional. - # """ - - parameters: Optional[Dict[str, Any]] - # """ - # Additional model-specific parameters. Refer to the [model guide](https://docs.pinecone.io/guides/inference/understanding-inference#models) - # for available model parameters. - # Optional. - # """ - - query: Optional[str] - # """ - # The query to rerank documents against. If a specific rerank query is specified, it overwrites - # the query input that was provided at the top level. - # """ diff --git a/pinecone/data/types/sparse_vector_typed_dict.py b/pinecone/data/types/sparse_vector_typed_dict.py deleted file mode 100644 index 03faf9beb..000000000 --- a/pinecone/data/types/sparse_vector_typed_dict.py +++ /dev/null @@ -1,6 +0,0 @@ -from typing import TypedDict, List - - -class SparseVectorTypedDict(TypedDict): - indices: List[int] - values: List[float] diff --git a/pinecone/data/types/vector_metadata_dict.py b/pinecone/data/types/vector_metadata_dict.py deleted file mode 100644 index 3eae355b7..000000000 --- a/pinecone/data/types/vector_metadata_dict.py +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Dict, List, Union - -VectorDictMetadataValue = Union[str, int, float, List[str], List[int], List[float]] -VectorMetadataTypedDict = Dict[str, VectorDictMetadataValue] diff --git a/pinecone/data/types/vector_tuple.py b/pinecone/data/types/vector_tuple.py deleted file mode 100644 index e15d7e7cf..000000000 --- a/pinecone/data/types/vector_tuple.py +++ /dev/null @@ -1,5 +0,0 @@ -from .vector_metadata_dict import VectorMetadataTypedDict -from typing import Tuple, List - -VectorTuple = Tuple[str, List[float]] -VectorTupleWithMetadata = Tuple[str, List[float], VectorMetadataTypedDict] diff --git a/pinecone/data/types/vector_typed_dict.py b/pinecone/data/types/vector_typed_dict.py deleted file mode 100644 index 20c1e6e7d..000000000 --- a/pinecone/data/types/vector_typed_dict.py +++ /dev/null @@ -1,9 +0,0 @@ -from .sparse_vector_typed_dict import SparseVectorTypedDict -from typing import TypedDict, List - - -class VectorTypedDict(TypedDict, total=False): - values: List[float] - metadata: dict - sparse_values: SparseVectorTypedDict - id: str diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py deleted file mode 100644 index 5ef54a0ba..000000000 --- a/pinecone/data/vector_factory.py +++ /dev/null @@ -1,109 +0,0 @@ -import numbers - -from collections.abc import Iterable, Mapping -from typing import Union, Tuple - -from ..utils import fix_tuple_length, convert_to_list, parse_non_empty_args -from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS - -from .sparse_values_factory import SparseValuesFactory - -from pinecone.core.openapi.db_data.models import ( - Vector as OpenApiVector, - SparseValues as OpenApiSparseValues, -) -from .dataclasses import Vector - -from .errors import ( - VectorDictionaryMissingKeysError, - VectorDictionaryExcessKeysError, - VectorTupleLengthError, - MetadataDictionaryExpectedError, -) - -from .types import VectorTuple, VectorTypedDict - - -class VectorFactory: - """VectorFactory is used to convert various types of input into vector objects used in generated request code.""" - - @staticmethod - def build( - item: Union[OpenApiVector, VectorTuple, VectorTypedDict], check_type: bool = True - ) -> OpenApiVector: - if isinstance(item, OpenApiVector): - return item - elif isinstance(item, Vector): - args = parse_non_empty_args( - [ - ("id", item.id), - ("values", item.values), - ("metadata", item.metadata), - ("sparse_values", SparseValuesFactory.build(item.sparse_values)), - ] - ) - - return OpenApiVector(**args) - elif isinstance(item, tuple): - return VectorFactory._tuple_to_vector(item, check_type) - elif isinstance(item, Mapping): - 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: Tuple, check_type: bool) -> OpenApiVector: - if len(item) < 2 or len(item) > 3: - raise VectorTupleLengthError(item) - id, values, metadata = fix_tuple_length(item, 3) - if isinstance(values, OpenApiSparseValues): - raise ValueError( - "Sparse values are not supported in tuples. Please use either dicts or OpenApiVector objects as inputs." - ) - else: - return OpenApiVector( - id=id, - values=convert_to_list(values), - metadata=metadata or {}, - _check_type=check_type, - ) - - @staticmethod - def _dict_to_vector(item, check_type: bool) -> OpenApiVector: - item_keys = set(item.keys()) - if not item_keys.issuperset(REQUIRED_VECTOR_FIELDS): - raise VectorDictionaryMissingKeysError(item) - - if "sparse_values" not in item_keys and "values" not in item_keys: - raise ValueError( - "At least one of 'values' or 'sparse_values' must be provided in the vector dictionary." - ) - - excessive_keys = item_keys - (REQUIRED_VECTOR_FIELDS | OPTIONAL_VECTOR_FIELDS) - if len(excessive_keys) > 0: - raise VectorDictionaryExcessKeysError(item) - - values = item.get("values") - if "values" in item: - item["values"] = convert_to_list(values) - else: - item["values"] = [] - - sparse_values = item.get("sparse_values") - if sparse_values is None: - item.pop("sparse_values", None) - else: - item["sparse_values"] = SparseValuesFactory.build(sparse_values) - - metadata = item.get("metadata") - if metadata and not isinstance(metadata, Mapping): - raise MetadataDictionaryExpectedError(item) - - try: - return OpenApiVector(**item, _check_type=check_type) - except TypeError as e: - if not isinstance(item["values"], Iterable) or not isinstance( - item["values"].__iter__().__next__(), numbers.Real - ): - raise TypeError("Column `values` is expected to be a list of floats") - raise e diff --git a/pinecone/deprecated_plugins.py b/pinecone/deprecated_plugins.py deleted file mode 100644 index 0a6c39394..000000000 --- a/pinecone/deprecated_plugins.py +++ /dev/null @@ -1,22 +0,0 @@ -class DeprecatedPluginError(Exception): - def __init__(self, plugin_name: str) -> None: - message = f"The `{plugin_name}` package has been deprecated. The features from that plugin have been incorporated into the main `pinecone` package with no need for additional plugins. Please remove the `{plugin_name}` package from your dependencies to ensure you have the most up-to-date version of these features." - super().__init__(message) - - -def check_for_deprecated_plugins(): - try: - from pinecone_plugins.inference import __installables__ # type: ignore - - if __installables__ is not None: - raise DeprecatedPluginError("pinecone-plugin-inference") - except ImportError: - pass - - try: - from pinecone_plugins.records import __installables__ # type: ignore - - if __installables__ is not None: - raise DeprecatedPluginError("pinecone-plugin-records") - except ImportError: - pass diff --git a/pinecone/deprecation_warnings.py b/pinecone/deprecation_warnings.py deleted file mode 100644 index ec458e781..000000000 --- a/pinecone/deprecation_warnings.py +++ /dev/null @@ -1,159 +0,0 @@ -def _build_class_migration_message(method_name: str, example: str): - return f"""{method_name} is no longer a top-level attribute of the pinecone package. - -To use {method_name}, please create a client instance and call the method there instead. - -Example: -{example} -""" - - -def init(*args, **kwargs): - example = """ - import os - from pinecone import Pinecone, ServerlessSpec - - pc = Pinecone( - api_key=os.environ.get("PINECONE_API_KEY") - ) - - # Now do stuff - if 'my_index' not in pc.list_indexes().names(): - pc.create_index( - name='my_index', - dimension=1536, - metric='euclidean', - spec=ServerlessSpec( - cloud='aws', - region='us-west-2' - ) - ) -""" - msg = f"""init is no longer a top-level attribute of the pinecone package. - -Please create an instance of the Pinecone class instead. - -Example: -{example} -""" - raise AttributeError(msg) - - -def list_indexes(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - - index_name = "quickstart" # or your index name - - if index_name not in pc.list_indexes().names(): - # do something -""" - raise AttributeError(_build_class_migration_message("list_indexes", example)) - - -def describe_index(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.describe_index('my_index') -""" - raise AttributeError(_build_class_migration_message("describe_index", example)) - - -def create_index(*args, **kwargs): - example = """ - from pinecone import Pinecone, ServerlessSpec - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.create_index( - name='my-index', - dimension=1536, - metric='euclidean', - spec=ServerlessSpec( - cloud='aws', - region='us-west-2' - ) - ) -""" - raise AttributeError(_build_class_migration_message("create_index", example)) - - -def delete_index(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.delete_index('my_index') -""" - raise AttributeError(_build_class_migration_message("delete_index", example)) - - -def scale_index(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.configure_index('my_index', replicas=2) -""" - - msg = f"""scale_index is no longer a top-level attribute of the pinecone package. - -Please create a client instance and call the configure_index method instead. - -Example: -{example} -""" - raise AttributeError(msg) - - -def create_collection(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.create_collection(name='my_collection', source='my_index') -""" - raise AttributeError(_build_class_migration_message("create_collection", example)) - - -def list_collections(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.list_collections() -""" - raise AttributeError(_build_class_migration_message("list_collections", example)) - - -def delete_collection(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.delete_collection('my_collection') -""" - raise AttributeError(_build_class_migration_message("delete_collection", example)) - - -def describe_collection(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.describe_collection('my_collection') -""" - raise AttributeError(_build_class_migration_message("describe_collection", example)) - - -def configure_index(*args, **kwargs): - example = """ - from pinecone import Pinecone - - pc = Pinecone(api_key='YOUR_API_KEY') - pc.configure_index('my_index', replicas=2) -""" - raise AttributeError(_build_class_migration_message("configure_index", example)) diff --git a/pinecone/enums/__init__.py b/pinecone/enums/__init__.py deleted file mode 100644 index 38d11eb36..000000000 --- a/pinecone/enums/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -from .clouds import CloudProvider, AwsRegion, GcpRegion, AzureRegion -from .deletion_protection import DeletionProtection -from .metric import Metric -from .pod_index_environment import PodIndexEnvironment -from .pod_type import PodType -from .vector_type import VectorType - -__all__ = [ - "CloudProvider", - "AwsRegion", - "GcpRegion", - "AzureRegion", - "DeletionProtection", - "Metric", - "PodIndexEnvironment", - "PodType", - "VectorType", -] diff --git a/pinecone/enums/clouds.py b/pinecone/enums/clouds.py deleted file mode 100644 index 192b3da5f..000000000 --- a/pinecone/enums/clouds.py +++ /dev/null @@ -1,54 +0,0 @@ -from enum import Enum - - -class CloudProvider(Enum): - """Cloud providers available for use with Pinecone serverless indexes - - This list could expand or change over time as more cloud providers are supported. - Check the Pinecone documentation for the most up-to-date list of supported cloud - providers. If you want to use a cloud provider that is not listed here, you can - pass a string value directly without using this enum. - """ - - AWS = "aws" - GCP = "gcp" - AZURE = "azure" - - -class AwsRegion(Enum): - """AWS (Amazon Web Services) regions available for use with Pinecone serverless indexes - - This list could expand or change over time as more regions are supported. - Check the Pinecone documentation for the most up-to-date list of supported - regions. If you want to use a region that is not listed here, you can - pass a string value directly without using this enum. - """ - - US_EAST_1 = "us-east-1" - US_WEST_2 = "us-west-2" - EU_WEST_1 = "eu-west-1" - - -class GcpRegion(Enum): - """GCP (Google Cloud Platform) regions available for use with Pinecone serverless indexes - - This list could expand or change over time as more regions are supported. - Check the Pinecone documentation for the most up-to-date list of supported - regions. If you want to use a region that is not listed here, you can - pass a string value directly without using this enum. - """ - - US_CENTRAL1 = "us-central1" - EUROPE_WEST4 = "europe-west4" - - -class AzureRegion(Enum): - """Azure regions available for use with Pinecone serverless indexes - - This list could expand or change over time as more regions are supported. - Check the Pinecone documentation for the most up-to-date list of supported - regions. If you want to use a region that is not listed here, you can - pass a string value directly without using this enum. - """ - - EASTUS2 = "eastus2" diff --git a/pinecone/enums/deletion_protection.py b/pinecone/enums/deletion_protection.py deleted file mode 100644 index 8dd13d69c..000000000 --- a/pinecone/enums/deletion_protection.py +++ /dev/null @@ -1,15 +0,0 @@ -from enum import Enum - - -class DeletionProtection(Enum): - """The DeletionProtection setting of an index indicates whether the index - can be the index cannot be deleted using the delete_index() method. - - If disabled, the index can be deleted. If enabled, calling delete_index() - will raise an error. - - This setting can be changed using the configure_index() method. - """ - - ENABLED = "enabled" - DISABLED = "disabled" diff --git a/pinecone/enums/metric.py b/pinecone/enums/metric.py deleted file mode 100644 index c3488220b..000000000 --- a/pinecone/enums/metric.py +++ /dev/null @@ -1,11 +0,0 @@ -from enum import Enum - - -class Metric(Enum): - """ - The metric specifies how Pinecone should calculate the distance between vectors when querying an index. - """ - - COSINE = "cosine" - EUCLIDEAN = "euclidean" - DOTPRODUCT = "dotproduct" diff --git a/pinecone/enums/pod_index_environment.py b/pinecone/enums/pod_index_environment.py deleted file mode 100644 index 13b9fa871..000000000 --- a/pinecone/enums/pod_index_environment.py +++ /dev/null @@ -1,20 +0,0 @@ -from enum import Enum - - -class PodIndexEnvironment(Enum): - """ - These environment strings are used to specify where a pod index should be deployed. - """ - - US_WEST1_GCP = "us-west1-gcp" - US_CENTRAL1_GCP = "us-central1-gcp" - US_WEST4_GCP = "us-west4-gcp" - US_EAST4_GCP = "us-east4-gcp" - NORTHAMERICA_NORTHEAST1_GCP = "northamerica-northeast1-gcp" - ASIA_NORTHEAST1_GCP = "asia-northeast1-gcp" - ASIA_SOUTHEAST1_GCP = "asia-southeast1-gcp" - US_EAST1_GCP = "us-east1-gcp" - EU_WEST1_GCP = "eu-west1-gcp" - EU_WEST4_GCP = "eu-west4-gcp" - US_EAST1_AWS = "us-east-1-aws" - EASTUS_AZURE = "eastus-azure" diff --git a/pinecone/enums/pod_type.py b/pinecone/enums/pod_type.py deleted file mode 100644 index 2e947c85b..000000000 --- a/pinecone/enums/pod_type.py +++ /dev/null @@ -1,20 +0,0 @@ -from enum import Enum - - -class PodType(Enum): - """ - PodType represents the available pod types for a pod index. - """ - - P1_X1 = "p1.x1" - P1_X2 = "p1.x2" - P1_X4 = "p1.x4" - P1_X8 = "p1.x8" - S1_X1 = "s1.x1" - S1_X2 = "s1.x2" - S1_X4 = "s1.x4" - S1_X8 = "s1.x8" - P2_X1 = "p2.x1" - P2_X2 = "p2.x2" - P2_X4 = "p2.x4" - P2_X8 = "p2.x8" diff --git a/pinecone/enums/vector_type.py b/pinecone/enums/vector_type.py deleted file mode 100644 index cc3d6f31b..000000000 --- a/pinecone/enums/vector_type.py +++ /dev/null @@ -1,14 +0,0 @@ -from enum import Enum - - -class VectorType(Enum): - """ - VectorType is used to specifiy the type of vector you will store in the index. - - Dense vectors are used to store dense embeddings, which are vectors with non-zero values in most of the dimensions. - - Sparse vectors are used to store sparse embeddings, which allow vectors with zero values in most of the dimensions to be represented concisely. - """ - - DENSE = "dense" - SPARSE = "sparse" diff --git a/pinecone/exceptions/__init__.py b/pinecone/exceptions/__init__.py deleted file mode 100644 index 92b05fd79..000000000 --- a/pinecone/exceptions/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -from pinecone.openapi_support.exceptions import ( - PineconeException, - PineconeApiAttributeError, - PineconeApiTypeError, - PineconeApiValueError, - PineconeApiKeyError, - PineconeApiException, - NotFoundException, - UnauthorizedException, - ForbiddenException, - ServiceException, -) -from .exceptions import PineconeConfigurationError, PineconeProtocolError, ListConversionException - -__all__ = [ - "PineconeConfigurationError", - "PineconeProtocolError", - "PineconeException", - "PineconeApiAttributeError", - "PineconeApiTypeError", - "PineconeApiValueError", - "PineconeApiKeyError", - "PineconeApiException", - "NotFoundException", - "UnauthorizedException", - "ForbiddenException", - "ServiceException", - "ListConversionException", -] diff --git a/pinecone/exceptions/exceptions.py b/pinecone/exceptions/exceptions.py deleted file mode 100644 index 3860dc8b1..000000000 --- a/pinecone/exceptions/exceptions.py +++ /dev/null @@ -1,14 +0,0 @@ -from pinecone.openapi_support.exceptions import PineconeException - - -class PineconeProtocolError(PineconeException): - """Raised when something unexpected happens mid-request/response.""" - - -class PineconeConfigurationError(PineconeException): - """Raised when a configuration error occurs.""" - - -class ListConversionException(PineconeException, TypeError): - def __init__(self, message): - super().__init__(message) diff --git a/pinecone/grpc/__init__.py b/pinecone/grpc/__init__.py deleted file mode 100644 index 350047ca1..000000000 --- a/pinecone/grpc/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -""" -Connecting to Pinecone with GRPC - -The `pinecone.grpc` submodule provides an alternative version of the Pinecone -client that uses gRPC instead of HTTP for data operations. This provides a -significant performance boost for data operations. - -### Installing the gRPC client - -You must install extra dependencies in order to install the GRPC client. - -#### Installing with pip - -```bash -# Install the latest version -pip3 install pinecone[grpc] - -# Install a specific version -pip3 install "pinecone[grpc]"==3.0.0 -``` - -#### Installing with poetry - -```bash -# Install the latest version -poetry add pinecone --extras grpc - -# Install a specific version -poetry add pinecone==3.0.0 --extras grpc -``` - -### Using the gRPC client - -```python -import os -from pinecone.grpc import PineconeGRPC - -client = PineconeGRPC(api_key=os.environ.get("PINECONE_API_KEY")) - -# From this point on, usage is identical to the HTTP client. -index = client.Index(host=os.environ("PINECONE_INDEX_HOST")) -index.query(vector=[...], top_k=10) -``` - -""" - -from .index_grpc import GRPCIndex -from .pinecone import PineconeGRPC -from .config import GRPCClientConfig -from .future import PineconeGrpcFuture - -from pinecone.data.dataclasses import Vector, SparseValues - -from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( - Vector as GRPCVector, - SparseValues as GRPCSparseValues, - DeleteResponse as GRPCDeleteResponse, -) - -__all__ = [ - "GRPCIndex", - "PineconeGRPC", - "GRPCDeleteResponse", - "GRPCClientConfig", - "GRPCVector", - "GRPCSparseValues", - "Vector", - "SparseValues", - "PineconeGrpcFuture", -] diff --git a/pinecone/grpc/base.py b/pinecone/grpc/base.py deleted file mode 100644 index 5c99305bb..000000000 --- a/pinecone/grpc/base.py +++ /dev/null @@ -1,95 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Optional - -import grpc -from grpc._channel import Channel - -from .channel_factory import GrpcChannelFactory - -from pinecone import Config -from .config import GRPCClientConfig -from .grpc_runner import GrpcRunner -from concurrent.futures import ThreadPoolExecutor - - -class GRPCIndexBase(ABC): - """ - Base class for grpc-based interaction with Pinecone indexes - """ - - _pool = None - - def __init__( - self, - index_name: str, - config: Config, - channel: Optional[Channel] = None, - grpc_config: Optional[GRPCClientConfig] = None, - pool_threads: Optional[int] = None, - _endpoint_override: Optional[str] = None, - ): - self.config = config - self.grpc_client_config = grpc_config or GRPCClientConfig() - self.pool_threads = pool_threads - - self._endpoint_override = _endpoint_override - - self.runner = GrpcRunner( - index_name=index_name, config=config, grpc_config=self.grpc_client_config - ) - self.channel_factory = GrpcChannelFactory( - config=self.config, grpc_client_config=self.grpc_client_config, use_asyncio=False - ) - self._channel = channel or self._gen_channel() - self.stub = self.stub_class(self._channel) - - @property - def threadpool_executor(self): - if self._pool is None: - pt = self.pool_threads or 10 - self._pool = ThreadPoolExecutor(max_workers=pt) - return self._pool - - @property - @abstractmethod - def stub_class(self): - pass - - def _endpoint(self): - grpc_host = self.config.host.replace("https://", "") - if ":" not in grpc_host: - grpc_host = f"{grpc_host}:443" - return self._endpoint_override if self._endpoint_override else grpc_host - - def _gen_channel(self): - return self.channel_factory.create_channel(self._endpoint()) - - @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 __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() diff --git a/pinecone/grpc/channel_factory.py b/pinecone/grpc/channel_factory.py deleted file mode 100644 index 4a302947f..000000000 --- a/pinecone/grpc/channel_factory.py +++ /dev/null @@ -1,101 +0,0 @@ -import logging -from typing import Optional - -import certifi -import grpc -import json - -from pinecone import Config -from .config import GRPCClientConfig -from pinecone.utils.constants import MAX_MSG_SIZE -from pinecone.utils.user_agent import get_user_agent_grpc - -_logger = logging.getLogger(__name__) -""" @private """ - - -class GrpcChannelFactory: - def __init__( - self, - config: Config, - grpc_client_config: GRPCClientConfig, - use_asyncio: Optional[bool] = False, - ): - self.config = config - self.grpc_client_config = grpc_client_config - self.use_asyncio = use_asyncio - - def _get_service_config(self): - # https://github.com/grpc/grpc-proto/blob/master/grpc/service_config/service_config.proto - return 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"], - }, - }, - ] - } - ) - - def _build_options(self, target): - # For property definitions, see https://github.com/grpc/grpc/blob/v1.43.x/include/grpc/impl/codegen/grpc_types.h - options = { - "grpc.max_send_message_length": MAX_MSG_SIZE, - "grpc.max_receive_message_length": MAX_MSG_SIZE, - "grpc.service_config": self._get_service_config(), - "grpc.enable_retries": True, - "grpc.per_rpc_retry_buffer_size": MAX_MSG_SIZE, - "grpc.primary_user_agent": get_user_agent_grpc(self.config), - } - if self.grpc_client_config.secure: - options["grpc.ssl_target_name_override"] = target.split(":")[0] - if self.config.proxy_url: - options["grpc.http_proxy"] = self.config.proxy_url - - options_tuple = tuple((k, v) for k, v in options.items()) - return options_tuple - - def _build_channel_credentials(self): - ca_certs = self.config.ssl_ca_certs if self.config.ssl_ca_certs else certifi.where() - root_cas = open(ca_certs, "rb").read() - channel_creds = grpc.ssl_channel_credentials(root_certificates=root_cas) - return channel_creds - - def create_channel(self, endpoint): - options_tuple = self._build_options(endpoint) - - _logger.debug( - "Creating new channel with endpoint %s options %s and config %s", - endpoint, - options_tuple, - self.grpc_client_config, - ) - - if not self.grpc_client_config.secure: - create_channel_fn = ( - grpc.aio.insecure_channel if self.use_asyncio else grpc.insecure_channel - ) - channel = create_channel_fn(endpoint, options=options_tuple) - else: - channel_creds = self._build_channel_credentials() - create_channel_fn = grpc.aio.secure_channel if self.use_asyncio else grpc.secure_channel - channel = create_channel_fn(endpoint, credentials=channel_creds, options=options_tuple) - - return channel diff --git a/pinecone/grpc/config.py b/pinecone/grpc/config.py deleted file mode 100644 index f92b55607..000000000 --- a/pinecone/grpc/config.py +++ /dev/null @@ -1,38 +0,0 @@ -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 secure: 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] - :param additional_metadata: Additional metadata to be sent to the server with each request. Note that this - metadata refers to [gRPC metadata](https://grpc.io/docs/guides/metadata/) which is a concept similar - to HTTP headers. This is unrelated to the metadata can be stored with a vector in the index. - :type additional_metadata: 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: Optional[Dict[str, str]] = None - additional_metadata: Optional[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/grpc/future.py b/pinecone/grpc/future.py deleted file mode 100644 index d98e1e84a..000000000 --- a/pinecone/grpc/future.py +++ /dev/null @@ -1,86 +0,0 @@ -from concurrent.futures import Future as ConcurrentFuture -from typing import Optional -from grpc import Future as GrpcFuture, RpcError -from pinecone.exceptions.exceptions import PineconeException - - -class PineconeGrpcFuture(ConcurrentFuture): - def __init__( - self, grpc_future: GrpcFuture, timeout: Optional[int] = None, result_transformer=None - ): - super().__init__() - self._grpc_future = grpc_future - self._result_transformer = result_transformer - if timeout is not None: - self._default_timeout = timeout # seconds - else: - self._default_timeout = 5 # seconds - - # Sync initial state, in case the gRPC future is already done - self._sync_state(self._grpc_future) - - # Add callback to subscribe to updates from the gRPC future - self._grpc_future.add_done_callback(self._sync_state) - - @property - def grpc_future(self): - return self._grpc_future - - def _sync_state(self, grpc_future): - if self.done(): - return - - if grpc_future.cancelled(): - self.cancel() - elif grpc_future.exception(timeout=self._default_timeout): - self.set_exception(grpc_future.exception()) - elif grpc_future.done(): - try: - result = grpc_future.result(timeout=self._default_timeout) - self.set_result(result) - except Exception as e: - self.set_exception(e) - elif grpc_future.running(): - self.set_running_or_notify_cancel() - - def set_result(self, result): - if self._result_transformer: - result = self._result_transformer(result) - return super().set_result(result) - - def cancel(self): - self._grpc_future.cancel() - return super().cancel() - - def exception(self, timeout=None): - exception = super().exception(timeout=self._timeout(timeout)) - if isinstance(exception, RpcError): - return self._wrap_rpc_exception(exception) - return exception - - def traceback(self, timeout=None): - # This is not part of the ConcurrentFuture interface, but keeping it for - # backward compatibility - return self._grpc_future.traceback(timeout=self._timeout(timeout)) - - def result(self, timeout=None): - try: - return super().result(timeout=self._timeout(timeout)) - except RpcError as e: - raise self._wrap_rpc_exception(e) from e - - def _timeout(self, timeout: Optional[int] = None) -> int: - if timeout is not None: - return timeout - else: - return self._default_timeout - - def _wrap_rpc_exception(self, e): - if e._state and e._state.debug_error_string: - return PineconeException(e._state.debug_error_string) - else: - return PineconeException("Unknown GRPC error") - - def __del__(self): - self._grpc_future.cancel() - self = None # release the reference to the grpc future diff --git a/pinecone/grpc/grpc_runner.py b/pinecone/grpc/grpc_runner.py deleted file mode 100644 index 253a6b33c..000000000 --- a/pinecone/grpc/grpc_runner.py +++ /dev/null @@ -1,97 +0,0 @@ -from functools import wraps -from typing import Dict, Tuple, Optional - -from grpc._channel import _InactiveRpcError - -from pinecone import Config -from .utils import _generate_request_id -from .config import GRPCClientConfig -from pinecone.utils.constants import REQUEST_ID, CLIENT_VERSION -from pinecone.exceptions.exceptions import PineconeException -from grpc import CallCredentials, Compression -from google.protobuf.message import Message - - -class GrpcRunner: - def __init__(self, index_name: str, config: Config, grpc_config: GRPCClientConfig): - self.config = config - self.grpc_client_config = grpc_config - - self.fixed_metadata = { - "api-key": config.api_key, - "service-name": index_name, - "client-version": CLIENT_VERSION, - } - if self.grpc_client_config.additional_metadata: - self.fixed_metadata.update(self.grpc_client_config.additional_metadata) - - def run( - self, - func, - request: Message, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - credentials: Optional[CallCredentials] = None, - wait_for_ready: Optional[bool] = None, - compression: Optional[Compression] = None, - ): - @wraps(func) - def wrapped(): - user_provided_metadata = metadata or {} - _metadata = self._prepare_metadata(user_provided_metadata) - 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() - - async def run_asyncio( - self, - func, - request: Message, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - credentials: Optional[CallCredentials] = None, - wait_for_ready: Optional[bool] = None, - compression: Optional[Compression] = None, - ): - @wraps(func) - async def wrapped(): - user_provided_metadata = metadata or {} - _metadata = self._prepare_metadata(user_provided_metadata) - try: - return await 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 await wrapped() - - def _prepare_metadata( - self, user_provided_metadata: Dict[str, str] - ) -> Tuple[Tuple[str, str], ...]: - return tuple( - (k, v) - for k, v in { - **self.fixed_metadata, - **self._request_metadata(), - **user_provided_metadata, - }.items() - ) - - def _request_metadata(self) -> Dict[str, str]: - return {REQUEST_ID: _generate_request_id()} diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py deleted file mode 100644 index eeac20ff3..000000000 --- a/pinecone/grpc/index_grpc.py +++ /dev/null @@ -1,644 +0,0 @@ -import logging -from typing import Optional, Dict, Union, List, Tuple, Any, Iterable, cast, Literal - -from google.protobuf import json_format - -from pinecone.utils.tqdm import tqdm -from concurrent.futures import as_completed, Future - - -from .utils import ( - dict_to_proto_struct, - parse_fetch_response, - parse_query_response, - parse_stats_response, -) -from .vector_factory_grpc import VectorFactoryGRPC -from .sparse_values_factory import SparseValuesFactory - -from pinecone.core.openapi.db_data.models import ( - FetchResponse, - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, -) -from pinecone.models.list_response import ListResponse as SimpleListResponse, Pagination -from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( - Vector as GRPCVector, - QueryVector as GRPCQueryVector, - UpsertRequest, - UpsertResponse, - DeleteRequest, - QueryRequest, - FetchRequest, - UpdateRequest, - ListRequest, - DescribeIndexStatsRequest, - DeleteResponse, - UpdateResponse, - SparseValues as GRPCSparseValues, -) -from pinecone import Vector, SparseValues -from pinecone.data.query_results_aggregator import QueryNamespacesResults, QueryResultsAggregator -from pinecone.core.grpc.protos.db_data_2025_01_pb2_grpc import VectorServiceStub -from .base import GRPCIndexBase -from .future import PineconeGrpcFuture -from ..data.types import ( - SparseVectorTypedDict, - VectorTypedDict, - VectorTuple, - FilterTypedDict, - VectorMetadataTypedDict, -) - - -__all__ = ["GRPCIndex", "GRPCVector", "GRPCQueryVector", "GRPCSparseValues"] - -_logger = logging.getLogger(__name__) -""" @private """ - - -class GRPCIndex(GRPCIndexBase): - """A client for interacting with a Pinecone index via GRPC API.""" - - @property - def stub_class(self): - return VectorServiceStub - - def upsert( - self, - vectors: Union[List[Vector], List[GRPCVector], List[VectorTuple], List[VectorTypedDict]], - async_req: bool = False, - namespace: Optional[str] = None, - batch_size: Optional[int] = None, - show_progress: bool = True, - **kwargs, - ) -> Union[UpsertResponse, PineconeGrpcFuture]: - """ - 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. - - Examples: - >>> index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), - ('id2', [1.0, 2.0, 3.0]) - ], - namespace='ns1', async_req=True) - >>> index.upsert([{'id': 'id1', 'values': [1.0, 2.0, 3.0], 'metadata': {'key': 'value'}}, - {'id': 'id2', - 'values': [1.0, 2.0, 3.0], - '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]), - GRPCVector(id='id3', - values=[1.0, 2.0, 3.0], - sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4]))]) - - Args: - vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. - - A vector can be represented by a 1) GRPCVector object, a 2) tuple or 3) a dictionary - 1) if a tuple is used, it must be of the form (id, values, metadata) or (id, values). - where id is a string, vector is a list of floats, and metadata is a dict. - Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) - - 2) if a GRPCVector object is used, a GRPCVector object must be of the form - GRPCVector(id, values, metadata), where metadata is an optional argument of type - Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] - Examples: GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), - GRPCVector(id='id2', values=[1.0, 2.0, 3.0]), - GRPCVector(id='id3', - values=[1.0, 2.0, 3.0], - sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4])) - - 3) if a dictionary is used, it must be in the form - {'id': str, 'values': List[float], 'sparse_values': {'indices': List[int], 'values': List[float]}, - 'metadata': dict} - - Note: the dimension of each vector must match the dimension of the index. - async_req (bool): If True, the upsert operation will be performed asynchronously. - Cannot be used with batch_size. - Defaults to False. See: https://docs.pinecone.io/docs/performance-tuning [optional] - namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - batch_size (int): The number of vectors to upsert in each batch. - Cannot be used with async_req=True. - If not specified, all vectors will be upserted in a single batch. [optional] - show_progress (bool): Whether to show a progress bar using tqdm. - Applied only if batch_size is provided. Default is True. - - Returns: UpsertResponse, contains the number of vectors upserted - """ - if async_req and batch_size is not None: - raise ValueError( - "async_req is not supported when batch_size is provided." - "To upsert in parallel, please follow: " - "https://docs.pinecone.io/docs/performance-tuning" - ) - - timeout = kwargs.pop("timeout", None) - - 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) - future = self.runner.run(self.stub.Upsert.future, request, timeout=timeout) - return PineconeGrpcFuture(future) - - if batch_size is None: - return self._upsert_batch(vectors, namespace, timeout=timeout, **kwargs) - - if not isinstance(batch_size, int) or batch_size <= 0: - raise ValueError("batch_size must be a positive integer") - - pbar = tqdm(total=len(vectors), disable=not show_progress, desc="Upserted vectors") - total_upserted = 0 - for i in range(0, len(vectors), batch_size): - batch_result = self._upsert_batch( - vectors[i : i + batch_size], namespace, timeout=timeout, **kwargs - ) - pbar.update(batch_result.upserted_count) - # we can't use here pbar.n for the case show_progress=False - total_upserted += batch_result.upserted_count - - return UpsertResponse(upserted_count=total_upserted) - - def _upsert_batch( - self, vectors: List[GRPCVector], namespace: Optional[str], timeout: Optional[int], **kwargs - ) -> UpsertResponse: - args_dict = self._parse_non_empty_args([("namespace", namespace)]) - request = UpsertRequest(vectors=vectors, **args_dict) - return self.runner.run(self.stub.Upsert, request, timeout=timeout, **kwargs) - - def upsert_from_dataframe( - self, - df, - namespace: str = "", - batch_size: int = 500, - use_async_requests: bool = True, - show_progress: bool = True, - ) -> UpsertResponse: - """Upserts a dataframe into the index. - - Args: - df: A pandas dataframe with the following columns: id, values, sparse_values, and metadata. - namespace: The namespace to upsert into. - batch_size: The number of rows to upsert in a single batch. - use_async_requests: Whether to upsert multiple requests at the same time using asynchronous request mechanism. - Set to `False` - show_progress: Whether to show a progress bar. - """ - try: - import pandas as pd - except ImportError: - raise RuntimeError( - "The `pandas` package is not installed. Please install pandas to use `upsert_from_dataframe()`" - ) - - if not isinstance(df, pd.DataFrame): - raise ValueError(f"Only pandas dataframes are supported. Found: {type(df)}") - - pbar = tqdm(total=len(df), disable=not show_progress, desc="sending upsert requests") - results = [] - for chunk in self._iter_dataframe(df, batch_size=batch_size): - res = self.upsert(vectors=chunk, namespace=namespace, async_req=use_async_requests) - pbar.update(len(chunk)) - results.append(res) - - if use_async_requests: - cast_results = cast(List[PineconeGrpcFuture], results) - results = [ - async_result.result() - for async_result in tqdm( - iterable=cast_results, - disable=not show_progress, - desc="collecting async responses", - ) - ] - - upserted_count = 0 - for res in results: - if hasattr(res, "upserted_count") and isinstance(res.upserted_count, int): - upserted_count += res.upserted_count - - return UpsertResponse(upserted_count=upserted_count) - - @staticmethod - def _iter_dataframe(df, batch_size): - for i in range(0, len(df), batch_size): - batch = df.iloc[i : i + batch_size].to_dict(orient="records") - yield batch - - def delete( - self, - ids: Optional[List[str]] = None, - delete_all: Optional[bool] = None, - namespace: Optional[str] = None, - filter: Optional[FilterTypedDict] = None, - async_req: bool = False, - **kwargs, - ) -> Union[DeleteResponse, PineconeGrpcFuture]: - """ - The Delete operation deletes vectors from the index, from a single namespace. - No error raised if the vector id does not exist. - Note: for any delete call, if namespace is not specified, the default namespace is used. - - Delete can occur in the following mutual exclusive ways: - 1. Delete by ids from a single namespace - 2. Delete all vectors from a single namespace by setting delete_all to True - 3. Delete all vectors from a single namespace by specifying a metadata filter - (note that for this option delete all must be set to False) - - Examples: - >>> index.delete(ids=['id1', 'id2'], namespace='my_namespace') - >>> index.delete(delete_all=True, namespace='my_namespace') - >>> index.delete(filter={'key': 'value'}, namespace='my_namespace', async_req=True) - - Args: - ids (List[str]): Vector ids to delete [optional] - delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] - Default is False. - namespace (str): The namespace to delete vectors from [optional] - If not specified, the default namespace is used. - filter (FilterTypedDict): - If specified, the metadata filter here will be used to select the vectors to delete. - This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. - See https://www.pinecone.io/docs/metadata-filtering/.. [optional] - async_req (bool): If True, the delete operation will be performed asynchronously. - Defaults to False. [optional] - - Returns: DeleteResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. - """ - - if filter is not None: - 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_struct), - ] - ) - timeout = kwargs.pop("timeout", None) - - request = DeleteRequest(**args_dict, **kwargs) - if async_req: - future = self.runner.run(self.stub.Delete.future, request, timeout=timeout) - return PineconeGrpcFuture(future) - else: - return self.runner.run(self.stub.Delete, request, timeout=timeout) - - def fetch( - self, - ids: Optional[List[str]], - namespace: Optional[str] = None, - async_req: Optional[bool] = False, - **kwargs, - ) -> Union[FetchResponse, PineconeGrpcFuture]: - """ - The fetch operation looks up and returns vectors, by ID, from a single namespace. - The returned vectors include the vector data and/or metadata. - - Examples: - >>> index.fetch(ids=['id1', 'id2'], namespace='my_namespace') - >>> index.fetch(ids=['id1', 'id2']) - - Args: - ids (List[str]): The vector IDs to fetch. - namespace (str): The namespace to fetch vectors from. - If not specified, the default namespace is used. [optional] - - Returns: FetchResponse object which contains the list of Vector objects, and namespace name. - """ - timeout = kwargs.pop("timeout", None) - - args_dict = self._parse_non_empty_args([("namespace", namespace)]) - - request = FetchRequest(ids=ids, **args_dict, **kwargs) - - if async_req: - future = self.runner.run(self.stub.Fetch.future, request, timeout=timeout) - return PineconeGrpcFuture(future, result_transformer=parse_fetch_response) - else: - response = self.runner.run(self.stub.Fetch, request, timeout=timeout) - return parse_fetch_response(response) - - def query( - self, - vector: Optional[List[float]] = None, - id: Optional[str] = None, - namespace: Optional[str] = None, - top_k: Optional[int] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[ - Union[SparseValues, GRPCSparseValues, SparseVectorTypedDict] - ] = None, - async_req: Optional[bool] = False, - **kwargs, - ) -> Union[QueryResponse, PineconeGrpcFuture]: - """ - 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. - - Examples: - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') - >>> index.query(id='id1', top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) - >>> index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) - >>> index.query(vector=[1, 2, 3], sparse_vector={'indices': [1, 2], 'values': [0.2, 0.4]}, - >>> top_k=10, namespace='my_namespace') - >>> index.query(vector=[1, 2, 3], sparse_vector=GRPCSparseValues([1, 2], [0.2, 0.4]), - >>> top_k=10, namespace='my_namespace') - - 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 - `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 - `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] - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - The filter to apply. You can use vector metadata to limit your search. - See https://www.pinecone.io/docs/metadata-filtering/.. [optional] - include_values (bool): Indicates whether vector values are included in the response. - If omitted the server will use the default value of False [optional] - include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. - If omitted the server will use the default value of False [optional] - sparse_vector: (Union[SparseValues, Dict[str, Union[List[float], List[int]]]]): sparse values of the query vector. - Expected to be either a SparseValues object or a dict of the form: - {'indices': List[int], 'values': List[float]}, where the lists each have the same length. - - Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, - and namespace name. - """ - - if vector is not None and id is not None: - raise ValueError("Cannot specify both `id` and `vector`") - - if filter is not None: - filter_struct = dict_to_proto_struct(filter) - else: - filter_struct = None - - sparse_vector = SparseValuesFactory.build(sparse_vector) - args_dict = self._parse_non_empty_args( - [ - ("vector", vector), - ("id", id), - ("namespace", namespace), - ("top_k", top_k), - ("filter", filter_struct), - ("include_values", include_values), - ("include_metadata", include_metadata), - ("sparse_vector", sparse_vector), - ] - ) - - request = QueryRequest(**args_dict) - - timeout = kwargs.pop("timeout", None) - - if async_req: - future = self.runner.run(self.stub.Query.future, request, timeout=timeout) - return PineconeGrpcFuture(future) - else: - response = self.runner.run(self.stub.Query, request, timeout=timeout) - json_response = json_format.MessageToDict(response) - return parse_query_response(json_response, _check_type=False) - - def query_namespaces( - self, - vector: List[float], - namespaces: List[str], - metric: Literal["cosine", "euclidean", "dotproduct"], - top_k: Optional[int] = None, - filter: Optional[FilterTypedDict] = None, - include_values: Optional[bool] = None, - include_metadata: Optional[bool] = None, - sparse_vector: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> QueryNamespacesResults: - if namespaces is None or len(namespaces) == 0: - raise ValueError("At least one namespace must be specified") - if len(vector) == 0: - raise ValueError("Query vector must not be empty") - - overall_topk = top_k if top_k is not None else 10 - aggregator = QueryResultsAggregator(top_k=overall_topk, metric=metric) - - target_namespaces = set(namespaces) # dedup namespaces - futures = [ - self.threadpool_executor.submit( - self.query, - vector=vector, - namespace=ns, - top_k=overall_topk, - filter=filter, - include_values=include_values, - include_metadata=include_metadata, - sparse_vector=sparse_vector, - async_req=False, - **kwargs, - ) - for ns in target_namespaces - ] - - only_futures = cast(Iterable[Future], futures) - for response in as_completed(only_futures): - aggregator.add_results(response.result()) - - final_results = aggregator.get_results() - return final_results - - def update( - self, - id: str, - async_req: bool = False, - values: Optional[List[float]] = None, - set_metadata: Optional[VectorMetadataTypedDict] = None, - namespace: Optional[str] = None, - sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, - **kwargs, - ) -> Union[UpdateResponse, PineconeGrpcFuture]: - """ - 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. - - Examples: - >>> index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') - >>> index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace', async_req=True) - >>> index.update(id='id1', values=[1, 2, 3], sparse_values={'indices': [1, 2], 'values': [0.2, 0.4]}, - >>> namespace='my_namespace') - >>> index.update(id='id1', values=[1, 2, 3], sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4]), - >>> namespace='my_namespace') - - Args: - id (str): Vector's unique id. - async_req (bool): If True, the update operation will be performed asynchronously. - Defaults to False. [optional] - values (List[float]): vector values to set. [optional] - set_metadata (Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]]): - metadata to set for vector. [optional] - namespace (str): Namespace name where to update the vector.. [optional] - sparse_values: (Dict[str, Union[List[float], List[int]]]): sparse values to update for the vector. - Expected to be either a GRPCSparseValues object or a dict of the form: - {'indices': List[int], 'values': List[float]} where the lists each have the same length. - - - Returns: UpdateResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. - """ - if set_metadata is not None: - set_metadata_struct = dict_to_proto_struct(set_metadata) - else: - set_metadata_struct = None - - timeout = kwargs.pop("timeout", None) - sparse_values = SparseValuesFactory.build(sparse_values) - args_dict = self._parse_non_empty_args( - [ - ("values", values), - ("set_metadata", set_metadata_struct), - ("namespace", namespace), - ("sparse_values", sparse_values), - ] - ) - - request = UpdateRequest(id=id, **args_dict) - if async_req: - future = self.runner.run(self.stub.Update.future, request, timeout=timeout) - return PineconeGrpcFuture(future) - else: - return self.runner.run(self.stub.Update, request, timeout=timeout) - - def list_paginated( - self, - prefix: Optional[str] = None, - limit: Optional[int] = None, - pagination_token: Optional[str] = None, - namespace: Optional[str] = None, - **kwargs, - ) -> SimpleListResponse: - """ - The list_paginated operation finds vectors based on an id prefix within a single namespace. - It returns matching ids in a paginated form, with a pagination token to fetch the next page of results. - This id list can then be passed to fetch or delete operations, depending on your use case. - - Consider using the `list` method to avoid having to handle pagination tokens manually. - - Examples: - >>> results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace') - >>> [v.id for v in results.vectors] - ['99', '990', '991', '992', '993'] - >>> results.pagination.next - eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9 - >>> next_results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace', pagination_token=results.pagination.next) - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - - Returns: SimpleListResponse object which contains the list of ids, the namespace name, pagination information, and usage showing the number of read_units consumed. - """ - args_dict = self._parse_non_empty_args( - [ - ("prefix", prefix), - ("limit", limit), - ("namespace", namespace), - ("pagination_token", pagination_token), - ] - ) - request = ListRequest(**args_dict, **kwargs) - timeout = kwargs.pop("timeout", None) - response = self.runner.run(self.stub.List, request, timeout=timeout) - - if response.pagination and response.pagination.next != "": - pagination = Pagination(next=response.pagination.next) - else: - pagination = None - - return SimpleListResponse( - namespace=response.namespace, vectors=response.vectors, pagination=pagination - ) - - def list(self, **kwargs): - """ - The list operation accepts all of the same arguments as list_paginated, and returns a generator that yields - a list of the matching vector ids in each page of results. It automatically handles pagination tokens on your - behalf. - - Examples: - >>> for ids in index.list(prefix='99', limit=5, namespace='my_namespace'): - >>> print(ids) - ['99', '990', '991', '992', '993'] - ['994', '995', '996', '997', '998'] - ['999'] - - Args: - prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will - be used with the effect of listing all ids in a namespace [optional] - limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional] - pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned - in the response if additional results are available. [optional] - namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - """ - done = False - while not done: - try: - results = self.list_paginated(**kwargs) - except Exception as e: - raise e - - if len(results.vectors) > 0: - yield [v.id for v in results.vectors] - - if results.pagination and results.pagination.next: - kwargs.update({"pagination_token": results.pagination.next}) - else: - done = True - - def describe_index_stats( - self, filter: Optional[FilterTypedDict] = None, **kwargs - ) -> DescribeIndexStatsResponse: - """ - The DescribeIndexStats operation returns statistics about the index's contents. - For example: The vector count per namespace and the number of dimensions. - - Examples: - >>> index.describe_index_stats() - >>> index.describe_index_stats(filter={'key': 'value'}) - - Args: - filter (Dict[str, Union[str, float, int, bool, List, dict]]): - 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] - - Returns: DescribeIndexStatsResponse object which contains stats about the index. - """ - if filter is not None: - 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) - response = self.runner.run(self.stub.DescribeIndexStats, request, timeout=timeout) - json_response = json_format.MessageToDict(response) - return parse_stats_response(json_response) - - @staticmethod - def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: - return {arg_name: val for arg_name, val in args if val is not None} diff --git a/pinecone/grpc/pinecone.py b/pinecone/grpc/pinecone.py deleted file mode 100644 index c78481ff6..000000000 --- a/pinecone/grpc/pinecone.py +++ /dev/null @@ -1,136 +0,0 @@ -from ..control.pinecone import Pinecone -from ..config.config import ConfigBuilder -from .index_grpc import GRPCIndex - - -class PineconeGRPC(Pinecone): - """ - An alternative version of the Pinecone client that uses gRPC instead of HTTP for - data operations. - - ### Installing the gRPC client - - You must install extra dependencies in order to install the GRPC client. - - #### Installing with pip - - ```bash - # Install the latest version - pip3 install pinecone[grpc] - - # Install a specific version - pip3 install "pinecone[grpc]"==3.0.0 - ``` - - #### Installing with poetry - - ```bash - # Install the latest version - poetry add pinecone --extras grpc - - # Install a specific version - poetry add pinecone==3.0.0 --extras grpc - ``` - - ### Using the gRPC client - - ```python - import os - from pinecone.grpc import PineconeGRPC - - client = PineconeGRPC(api_key=os.environ.get("PINECONE_API_KEY")) - - # From this point on, usage is identical to the HTTP client. - index = client.Index("my-index", host=os.environ("PINECONE_INDEX_HOST")) - index.query(...) - ``` - - """ - - def Index(self, name: str = "", host: str = "", **kwargs): - """ - Target an index for data operations. - - ### Target an index by host url - - In production situations, you want to uspert or query your data as quickly - as possible. If you know in advance the host url of your index, you can - eliminate a round trip to the Pinecone control plane by specifying the - host of the index. - - ```python - import os - from pinecone.grpc import PineconeGRPC - - api_key = os.environ.get("PINECONE_API_KEY") - index_host = os.environ.get("PINECONE_INDEX_HOST") - - pc = PineconeGRPC(api_key=api_key) - index = pc.Index(host=index_host) - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - - To find your host url, you can use the Pinecone control plane to describe - the index. The host url is returned in the response. Or, alternatively, the - host is displayed in the Pinecone web console. - - ```python - import os - from pinecone import Pinecone - - pc = Pinecone( - api_key=os.environ.get("PINECONE_API_KEY") - ) - - host = pc.describe_index('index-name').host - ``` - - ### Target an index by name (not recommended for production) - - For more casual usage, such as when you are playing and exploring with Pinecone - in a notebook setting, you can also target an index by name. If you use this - approach, the client may need to perform an extra call to the Pinecone control - plane to get the host url on your behalf to get the index host. - - The client will cache the index host for future use whenever it is seen, so you - will only incur the overhead of only one call. But this approach is not - recommended for production usage. - - ```python - import os - from pinecone import ServerlessSpec - from pinecone.grpc import PineconeGRPC - - api_key = os.environ.get("PINECONE_API_KEY") - - pc = PineconeGRPC(api_key=api_key) - pc.create_index( - name='my-index', - dimension=1536, - metric='cosine', - spec=ServerlessSpec(cloud='aws', region='us-west-2') - ) - index = pc.Index('my-index') - - # Now you're ready to perform data operations - index.query(vector=[...], top_k=10) - ``` - """ - if name == "" and host == "": - raise ValueError("Either name or host must be specified") - - # Use host if it is provided, otherwise get host from describe_index - index_host = host or self.index_host_store.get_host(self.index_api, self.config, name) - - pt = kwargs.pop("pool_threads", None) or self.pool_threads - - config = ConfigBuilder.build( - api_key=self.config.api_key, - host=index_host, - source_tag=self.config.source_tag, - proxy_url=self.config.proxy_url, - ssl_ca_certs=self.config.ssl_ca_certs, - ) - return GRPCIndex(index_name=name, config=config, pool_threads=pt, **kwargs) diff --git a/pinecone/grpc/retry.py b/pinecone/grpc/retry.py deleted file mode 100644 index 8ff1864e0..000000000 --- a/pinecone/grpc/retry.py +++ /dev/null @@ -1,90 +0,0 @@ -import abc -import logging -import random -import time -from typing import Optional, Tuple, NamedTuple - -import grpc - - -_logger = logging.getLogger(__name__) -""" @private """ - - -class SleepPolicy(abc.ABC): - @abc.abstractmethod - def sleep(self, try_i: int): - """ - How long to sleep in milliseconds. - :param try_i: the number of retry (starting from zero) - """ - assert try_i >= 0 - - -class ExponentialBackoff(SleepPolicy): - def __init__(self, *, init_backoff_ms: int, max_backoff_ms: int, multiplier: int): - self.init_backoff = random.randint(0, init_backoff_ms) - self.max_backoff = max_backoff_ms - self.multiplier = multiplier - - def sleep(self, try_i: int): - sleep_range = min(self.init_backoff * self.multiplier**try_i, self.max_backoff) - sleep_ms = random.randint(0, sleep_range) - _logger.debug(f"gRPC retry. Sleeping for {sleep_ms}ms") - time.sleep(sleep_ms / 1000) - - -class RetryOnRpcErrorClientInterceptor( - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, -): - """gRPC retry. - - Referece: https://github.com/grpc/grpc/issues/19514#issuecomment-531700657 - """ - - def __init__(self, retry_config: "RetryConfig"): - self.max_attempts = retry_config.max_attempts - self.sleep_policy = retry_config.sleep_policy - self.retryable_status = retry_config.retryable_status - - def _is_retryable_error(self, response_or_error): - """Determine if a response is a retryable error.""" - return ( - isinstance(response_or_error, grpc.RpcError) - and "_MultiThreadedRendezvous" not in response_or_error.__class__.__name__ - and response_or_error.code() in self.retryable_status - ) - - def _intercept_call(self, continuation, client_call_details, request_or_iterator): - response = None - for try_i in range(self.max_attempts): - response = continuation(client_call_details, request_or_iterator) - if not self._is_retryable_error(response): - break - self.sleep_policy.sleep(try_i) - return response - - def intercept_unary_unary(self, continuation, client_call_details, request): - return self._intercept_call(continuation, client_call_details, request) - - def intercept_unary_stream(self, continuation, client_call_details, request): - return self._intercept_call(continuation, client_call_details, request) - - def intercept_stream_unary(self, continuation, client_call_details, request_iterator): - return self._intercept_call(continuation, client_call_details, request_iterator) - - def intercept_stream_stream(self, continuation, client_call_details, request_iterator): - return self._intercept_call(continuation, client_call_details, request_iterator) - - -class RetryConfig(NamedTuple): - """Config settings related to retry""" - - 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,) diff --git a/pinecone/grpc/sparse_values_factory.py b/pinecone/grpc/sparse_values_factory.py deleted file mode 100644 index 240cd8e1c..000000000 --- a/pinecone/grpc/sparse_values_factory.py +++ /dev/null @@ -1,61 +0,0 @@ -from collections.abc import Mapping -from typing import Union, Optional - -from ..utils import convert_to_list - -from ..data import SparseValuesTypeError, SparseValuesMissingKeysError -from ..data.types import SparseVectorTypedDict - -from pinecone.core.grpc.protos.db_data_2025_01_pb2 import SparseValues as GRPCSparseValues -from pinecone.core.openapi.db_data.models import SparseValues as OpenApiSparseValues -from pinecone import SparseValues - - -class SparseValuesFactory: - @staticmethod - def build( - input: Optional[ - Union[SparseVectorTypedDict, SparseValues, GRPCSparseValues, OpenApiSparseValues] - ], - ) -> Optional[GRPCSparseValues]: - if input is None: - return input - if isinstance(input, GRPCSparseValues): - return input - if isinstance(input, SparseValues) or isinstance(input, OpenApiSparseValues): - return GRPCSparseValues( - indices=SparseValuesFactory._convert_to_list(input.indices, int), - values=SparseValuesFactory._convert_to_list(input.values, float), - ) - if isinstance(input, Mapping): - if not {"indices", "values"}.issubset(input): - raise SparseValuesMissingKeysError(input) - - indices = SparseValuesFactory._convert_to_list(input.get("indices"), int) - values = SparseValuesFactory._convert_to_list(input.get("values"), float) - - if len(indices) != len(values): - raise ValueError("Sparse values indices and values must have the same length") - - try: - return GRPCSparseValues(indices=indices, values=values) - except TypeError as e: - raise SparseValuesTypeError() from e - raise ValueError( - "SparseValuesFactory does not know how to handle input type {}".format(type(input)) - ) - - @staticmethod - def _convert_to_list(input, expected_type): - try: - converted = convert_to_list(input) - except TypeError as e: - raise SparseValuesTypeError() from e - - SparseValuesFactory._validate_list_items_type(converted, expected_type) - return converted - - @staticmethod - def _validate_list_items_type(input, expected_type): - if len(input) > 0 and not isinstance(input[0], expected_type): - raise SparseValuesTypeError() diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py deleted file mode 100644 index bd6540deb..000000000 --- a/pinecone/grpc/utils.py +++ /dev/null @@ -1,108 +0,0 @@ -from typing import Optional -from google.protobuf import json_format -from google.protobuf.message import Message - -import uuid - -from pinecone.core.openapi.db_data.models import ( - Vector as _Vector, - Usage, - ScoredVector, - SparseValues, - QueryResponse, - IndexDescription as DescribeIndexStatsResponse, - NamespaceSummary, -) -from pinecone.data.dataclasses import FetchResponse - -from google.protobuf.struct_pb2 import Struct - - -def _generate_request_id() -> str: - return str(uuid.uuid4()) - - -def dict_to_proto_struct(d: Optional[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: Message): - json_response = json_format.MessageToDict(response) - - vd = {} - vectors = json_response.get("vectors", {}) - namespace = json_response.get("namespace", "") - - for id, vec in vectors.items(): - 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, - ) - - return FetchResponse( - vectors=vd, namespace=namespace, usage=parse_usage(json_response.get("usage", {})) - ) - - -def parse_usage(usage: dict): - return Usage(read_units=int(usage.get("readUnits", 0))) - - -def parse_query_response(response: dict, _check_type: bool = False): - matches = [] - 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", None), - _check_type=_check_type, - ) - matches.append(sc) - - # Due to OpenAPI model classes / actual parsing cost, we want to avoid - # creating empty `Usage` objects and then passing them into QueryResponse - # when they are not actually present in the response from the server. - args = { - "namespace": response.get("namespace", ""), - "matches": matches, - "_check_type": _check_type, - } - usage = response.get("usage") - if usage: - args["usage"] = parse_usage(usage) - return QueryResponse(**args) - - -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/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py deleted file mode 100644 index 1fe9572b6..000000000 --- a/pinecone/grpc/vector_factory_grpc.py +++ /dev/null @@ -1,127 +0,0 @@ -import numbers - -from collections.abc import Iterable, Mapping -from typing import Union - -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, - MetadataDictionaryExpectedError, -) -from ..data.types import VectorTuple, VectorTypedDict -from .sparse_values_factory import SparseValuesFactory - -from pinecone.core.grpc.protos.db_data_2025_01_pb2 import ( - Vector as GRPCVector, - SparseValues as GRPCSparseValues, -) -from pinecone.core.openapi.db_data.models import ( - SparseValues as OpenApiSparseValues, - Vector as OpenApiVector, -) -from pinecone import Vector, SparseValues - - -class VectorFactoryGRPC: - """This class is responsible for building GRPCVector objects from various input types.""" - - @staticmethod - def build(item: Union[Vector, GRPCVector, Vector, VectorTuple, VectorTypedDict]) -> GRPCVector: - if isinstance(item, GRPCVector): - return item - elif isinstance(item, Vector) or isinstance(item, OpenApiVector): - if item.sparse_values: - sv = SparseValuesFactory.build(item.sparse_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, SparseValues) - or isinstance(values, OpenApiSparseValues) - ): - 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) - - if "values" not in item and "sparse_values" not in item: - raise ValueError( - "At least one of 'values' or 'sparse_values' must be provided in the vector dictionary." - ) - - values = item.get("values") - if "values" in item: - try: - item["values"] = convert_to_list(values) - except TypeError as e: - raise TypeError("Column `values` is expected to be a list of floats") from e - - sparse_values = item.get("sparse_values") - if sparse_values is not None: - item["sparse_values"] = SparseValuesFactory.build(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: - # Where possible raise a more specific error to the user. - vid = item.get("id") - if not isinstance(vid, bytes) and not isinstance(vid, str): - raise TypeError( - f"Cannot set Vector.id to {vid}: {vid} has type {type(vid)}, " - "but expected one of: (, ) for field Vector.id" - ) - if not isinstance(item["values"], Iterable) or not isinstance( - item["values"].__iter__().__next__(), numbers.Real - ): - raise TypeError("Column `values` is expected to be a list of floats") - raise e diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py deleted file mode 100644 index 86306c1e1..000000000 --- a/pinecone/models/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from .index_description import ServerlessSpecDefinition, PodSpecDefinition -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 -from .index_model import IndexModel -from .index_embed import IndexEmbed - -__all__ = [ - "CollectionDescription", - "PodSpec", - "PodSpecDefinition", - "ServerlessSpec", - "ServerlessSpecDefinition", - "IndexList", - "CollectionList", - "IndexModel", - "IndexEmbed", -] diff --git a/pinecone/models/collection_description.py b/pinecone/models/collection_description.py deleted file mode 100644 index a5e38ce65..000000000 --- a/pinecone/models/collection_description.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import NamedTuple - - -class CollectionDescription(NamedTuple): - """ - The description of a collection. - """ - - name: str - """ - The name of the collection. - """ - - source: str - """ - The name of the index used to create the collection. - """ diff --git a/pinecone/models/collection_list.py b/pinecone/models/collection_list.py deleted file mode 100644 index 508ec685a..000000000 --- a/pinecone/models/collection_list.py +++ /dev/null @@ -1,33 +0,0 @@ -import json -from pinecone.core.openapi.db_control.models import CollectionList as OpenAPICollectionList - - -class CollectionList: - """ - A list of collections. - """ - - def __init__(self, collection_list: OpenAPICollectionList): - self.collection_list = collection_list - self.current = 0 - - def names(self): - return [i["name"] for i in self.collection_list.collections] - - 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 json.dumps([c.to_dict() for c in self.collection_list.collections], indent=4) - - def __getattr__(self, attr): - return getattr(self.collection_list, attr) diff --git a/pinecone/models/index_description.py b/pinecone/models/index_description.py deleted file mode 100644 index 8518b925c..000000000 --- a/pinecone/models/index_description.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import NamedTuple, Dict, Optional, Literal - - -class PodSpecDefinition(NamedTuple): - replicas: int - shards: int - pods: int - pod_type: str - environment: str - metadata_config: Optional[Dict] - - -class ServerlessSpecDefinition(NamedTuple): - cloud: str - region: str - - -PodKey = Literal["pod"] -PodSpec = Dict[PodKey, PodSpecDefinition] - -ServerlessKey = Literal["serverless"] -ServerlessSpec = Dict[ServerlessKey, ServerlessSpecDefinition] diff --git a/pinecone/models/index_embed.py b/pinecone/models/index_embed.py deleted file mode 100644 index 4d1ccfe39..000000000 --- a/pinecone/models/index_embed.py +++ /dev/null @@ -1,68 +0,0 @@ -from dataclasses import dataclass -from typing import Optional, Dict, Any, Union - -from ..enums import Metric -from ..data.features.inference import EmbedModel - - -@dataclass(frozen=True) -class IndexEmbed: - """ - IndexEmbed represents the index embedding configuration when creating an index from a model. - """ - - model: str - """ - The name of the embedding model to use for the index. - Required. - """ - - field_map: Dict[str, Any] - """ - A mapping of field names to their types. - Required. - """ - - metric: Optional[str] = None - """ - The metric to use for the index. If not provided, the default metric for the model is used. - Optional. - """ - - read_parameters: Optional[Dict[str, Any]] = None - """ - The parameters to use when reading from the index. - Optional. - """ - - write_parameters: Optional[Dict[str, Any]] = None - """ - The parameters to use when writing to the index. - Optional. - """ - - def as_dict(self) -> Dict[str, Any]: - """ - Returns the IndexEmbed as a dictionary. - """ - return self.__dict__ - - def __init__( - self, - model: Union[EmbedModel, str], - field_map: Dict[str, Any], - metric: Optional[Union[Metric, str]] = None, - read_parameters: Optional[Dict[str, Any]] = None, - write_parameters: Optional[Dict[str, Any]] = None, - ): - object.__setattr__( - self, "model", model.value if isinstance(model, EmbedModel) else str(model) - ) - object.__setattr__(self, "field_map", field_map) - object.__setattr__(self, "metric", metric.value if isinstance(metric, Metric) else metric) - object.__setattr__( - self, "read_parameters", read_parameters if read_parameters is not None else {} - ) - object.__setattr__( - self, "write_parameters", write_parameters if write_parameters is not None else {} - ) diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py deleted file mode 100644 index 71242e24c..000000000 --- a/pinecone/models/index_list.py +++ /dev/null @@ -1,32 +0,0 @@ -import json -from pinecone.core.openapi.db_control.models import IndexList as OpenAPIIndexList -from .index_model import IndexModel -from typing import List - - -class IndexList: - def __init__(self, index_list: OpenAPIIndexList): - self.index_list = index_list - self.indexes = [IndexModel(i) for i in self.index_list.indexes] - self.current = 0 - - def names(self) -> List[str]: - return [i.name for i in self.indexes] - - def __getitem__(self, key): - return self.indexes[key] - - def __len__(self): - return len(self.indexes) - - def __iter__(self): - return iter(self.indexes) - - def __str__(self): - return str(self.indexes) - - def __repr__(self): - return json.dumps([i.to_dict() for i in self.indexes], indent=4) - - def __getattr__(self, attr): - return getattr(self.index_list, attr) diff --git a/pinecone/models/index_model.py b/pinecone/models/index_model.py deleted file mode 100644 index 7deb2d7d8..000000000 --- a/pinecone/models/index_model.py +++ /dev/null @@ -1,19 +0,0 @@ -from pinecone.core.openapi.db_control.models import IndexModel as OpenAPIIndexModel - - -class IndexModel: - def __init__(self, index: OpenAPIIndexModel): - self.index = index - self.deletion_protection = index.deletion_protection.value - - def __str__(self): - return str(self.index) - - def __getattr__(self, attr): - return getattr(self.index, attr) - - def __getitem__(self, key): - return self.__getattr__(key) - - def to_dict(self): - return self.index.to_dict() diff --git a/pinecone/models/list_response.py b/pinecone/models/list_response.py deleted file mode 100644 index c3ba57d41..000000000 --- a/pinecone/models/list_response.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import NamedTuple, Optional, List - - -class Pagination(NamedTuple): - next: str - - -class ListResponse(NamedTuple): - namespace: str - vectors: List - pagination: Optional[Pagination] diff --git a/pinecone/models/pod_spec.py b/pinecone/models/pod_spec.py deleted file mode 100644 index 2e6a41b9c..000000000 --- a/pinecone/models/pod_spec.py +++ /dev/null @@ -1,87 +0,0 @@ -from dataclasses import dataclass, field -from typing import Optional, Dict, Union - -from ..enums import PodIndexEnvironment, PodType - - -@dataclass(frozen=True) -class PodSpec: - """ - PodSpec represents the configuration used to deploy a pod-based index. - - To learn more about the options for each configuration, please see [Understanding Indexes](https://docs.pinecone.io/docs/indexes) - """ - - environment: str - """ - The environment where the pod index will be deployed. Example: 'us-east1-gcp' - """ - - replicas: Optional[int] = None - """ - The number of replicas to deploy for the pod index. Default: 1 - """ - - shards: Optional[int] = None - """ - The number of shards to use. Shards are used to expand the amount of vectors you can store beyond the capacity of a single pod. Default: 1 - """ - - pods: Optional[int] = None - """ - Number of pods to deploy. Default: 1 - """ - - pod_type: Optional[str] = "p1.x1" - """ - This value combines pod type and pod size into a single string. This configuration is your main lever for vertical scaling. - """ - - metadata_config: Optional[Dict] = field(default_factory=dict) - """ - If you are storing a lot of metadata, you can use this configuration to limit the fields which are indexed for search. - - This configuration should be a dictionary with the key 'indexed' and the value as a list of fields to index. - - Example: - ``` - {'indexed': ['field1', 'field2']} - ``` - """ - - source_collection: Optional[str] = None - """ - The name of the collection to use as the source for the pod index. This configuration is only used when creating a pod index from an existing collection. - """ - - def __init__( - self, - environment: Union[PodIndexEnvironment, str], - pod_type: Union[PodType, str] = "p1.x1", - replicas: Optional[int] = None, - shards: Optional[int] = None, - pods: Optional[int] = None, - metadata_config: Optional[Dict] = None, - source_collection: Optional[str] = None, - ): - object.__setattr__( - self, - "environment", - environment.value if isinstance(environment, PodIndexEnvironment) else str(environment), - ) - object.__setattr__( - self, "pod_type", pod_type.value if isinstance(pod_type, PodType) else str(pod_type) - ) - object.__setattr__(self, "replicas", replicas) - object.__setattr__(self, "shards", shards) - object.__setattr__(self, "pods", pods) - object.__setattr__( - self, "metadata_config", metadata_config if metadata_config is not None else {} - ) - object.__setattr__(self, "source_collection", source_collection) - - def asdict(self) -> Dict: - """ - Returns the PodSpec as a dictionary. - """ - return {"pod": self.__dict__} diff --git a/pinecone/models/serverless_spec.py b/pinecone/models/serverless_spec.py deleted file mode 100644 index 1fc515640..000000000 --- a/pinecone/models/serverless_spec.py +++ /dev/null @@ -1,25 +0,0 @@ -from dataclasses import dataclass -from typing import Union -from enum import Enum - -from ..enums import CloudProvider, AwsRegion, GcpRegion, AzureRegion - - -@dataclass(frozen=True) -class ServerlessSpec: - cloud: str - region: str - - def __init__( - self, - cloud: Union[CloudProvider, str], - region: Union[AwsRegion, GcpRegion, AzureRegion, str], - ): - # Convert Enums to their string values if necessary - object.__setattr__(self, "cloud", cloud.value if isinstance(cloud, Enum) else str(cloud)) - object.__setattr__( - self, "region", region.value if isinstance(region, Enum) else str(region) - ) - - def asdict(self): - return {"serverless": {"cloud": self.cloud, "region": self.region}} diff --git a/pinecone/openapi_support/__init__.py b/pinecone/openapi_support/__init__.py deleted file mode 100644 index 63e3fb0ae..000000000 --- a/pinecone/openapi_support/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# Items in this openapi_support package were extracted from the openapi generated code. -# Since we need to generate code off of multiple spec files, having these items in a -# generated output led to unnecessary duplication. Morever, these classes do not have -# any dynamic content so they didn't need to be part of the generation process. - -from .api_client import ApiClient -from .endpoint import Endpoint -from .endpoint_utils import ExtraOpenApiKwargsTypedDict, KwargsWithOpenApiKwargDefaultsTypedDict -from .asyncio_api_client import AsyncioApiClient -from .asyncio_endpoint import AsyncioEndpoint -from .configuration import Configuration -from .exceptions import ( - PineconeException, - PineconeApiAttributeError, - PineconeApiTypeError, - PineconeApiValueError, - PineconeApiKeyError, - PineconeApiException, - NotFoundException, - UnauthorizedException, - ForbiddenException, - ServiceException, -) -from .model_utils import ( - OpenApiModel, - ModelNormal, - ModelSimple, - ModelComposed, - change_keys_js_to_python, - convert_js_args_to_python_args, - validate_get_composed_info, - cached_property, - validate_and_convert_types, - check_allowed_values, - check_validations, - file_type, - none_type, -) -from .rest_urllib3 import Urllib3RestClient -from .rest_aiohttp import AiohttpRestClient -from .rest_utils import RESTResponse - -from .constants import OPENAPI_ENDPOINT_PARAMS - -from datetime import date, datetime # noqa: F401 -from dateutil.parser import parse - -from .types import PropertyValidationTypedDict -from .cached_class_property import cached_class_property diff --git a/pinecone/openapi_support/api_client.py b/pinecone/openapi_support/api_client.py deleted file mode 100644 index 421d56cc6..000000000 --- a/pinecone/openapi_support/api_client.py +++ /dev/null @@ -1,421 +0,0 @@ -import atexit -from multiprocessing.pool import ThreadPool -from concurrent.futures import ThreadPoolExecutor -import io - -from typing import Optional, List, Tuple, Dict, Any, Union -from .deserializer import Deserializer - - -from .rest_urllib3 import Urllib3RestClient -from .configuration import Configuration -from .exceptions import PineconeApiValueError, PineconeApiException -from .api_client_utils import ( - parameters_to_tuples, - files_parameters, - parameters_to_multipart, - process_params, - process_query_params, - build_request_url, -) -from .auth_util import AuthUtil -from .serializer import Serializer - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - :param configuration: .Configuration object for this client - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - _pool: Optional[ThreadPool] = None - _threadpool_executor: Optional[ThreadPoolExecutor] = None - - def __init__( - self, configuration: Optional[Configuration] = None, pool_threads: Optional[int] = 1 - ) -> None: - if configuration is None: - configuration = Configuration.get_default_copy() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = Urllib3RestClient(configuration) - - self.default_headers: Dict[str, str] = {} - self.user_agent = "OpenAPI-Generator/1.0.0/python" - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._threadpool_executor: - self._threadpool_executor.shutdown() - self._threadpool_executor = None - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - 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. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def threadpool_executor(self): - if self._threadpool_executor is None: - self._threadpool_executor = ThreadPoolExecutor(max_workers=self.pool_threads) - return self._threadpool_executor - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers["User-Agent"] - - @user_agent.setter - def user_agent(self, value): - self.default_headers["User-Agent"] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path: str, - method: str, - path_params: Optional[Dict[str, Any]] = None, - query_params: Optional[List[Tuple[str, Any]]] = None, - header_params: Optional[Dict[str, Any]] = None, - body: Optional[Any] = None, - post_params: Optional[List[Tuple[str, Any]]] = None, - files: Optional[Dict[str, List[io.IOBase]]] = None, - response_type: Optional[Tuple[Any]] = None, - auth_settings: Optional[List[str]] = None, - _return_http_data_only: Optional[bool] = True, - collection_formats: Optional[Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: Optional[Union[int, float, Tuple]] = None, - _host: Optional[str] = None, - _check_type: Optional[bool] = None, - ): - config = self.configuration - - path_params = path_params or {} - query_params = query_params or [] - header_params = header_params or {} - post_params = post_params or [] - files = files or {} - collection_formats = collection_formats or {} - - headers_tuple, path_params_tuple, sanitized_path_params = process_params( - default_headers=self.default_headers, - header_params=header_params, - path_params=path_params, - collection_formats=collection_formats, - ) - - processed_query_params = process_query_params(query_params, collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - sanitized_post_params = Serializer.sanitize_for_serialization(post_params) - if sanitized_path_params: - processed_post_params = parameters_to_tuples( - sanitized_post_params, collection_formats - ) - processed_post_params.extend(files_parameters(files)) - if headers_tuple["Content-Type"].startswith("multipart"): - processed_post_params = parameters_to_multipart(sanitized_post_params, (dict)) - else: - processed_post_params = None - - # body - if body: - body = Serializer.sanitize_for_serialization(body) - - # auth setting - AuthUtil.update_params_for_auth( - configuration=config, - endpoint_auth_settings=auth_settings, - headers=headers_tuple, - querys=processed_query_params, - ) - - url = build_request_url( - config=config, - processed_path_params=path_params_tuple, - resource_path=resource_path, - _host=_host, - ) - - try: - # perform request and return response - response_data = self.request( - method, - url, - query_params=processed_query_params, - headers=headers_tuple, - post_params=processed_post_params, - body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - except PineconeApiException as e: - 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 - - # deserialize response data - if response_type: - Deserializer.decode_response(response_type=response_type, response=response_data) - return_data = Deserializer.deserialize( - response=response_data, - response_type=response_type, - config=self.configuration, - _check_type=_check_type, - ) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return (return_data, response_data.status, response_data.getheaders()) - - def call_api( - self, - resource_path: str, - method: str, - path_params: Optional[Dict[str, Any]] = None, - query_params: Optional[List[Tuple[str, Any]]] = None, - header_params: Optional[Dict[str, Any]] = None, - body: Optional[Any] = None, - post_params: Optional[List[Tuple[str, Any]]] = None, - files: Optional[Dict[str, List[io.IOBase]]] = None, - response_type: Optional[Tuple[Any]] = None, - auth_settings: Optional[List[str]] = None, - async_req: Optional[bool] = None, - async_threadpool_executor: Optional[bool] = None, - _return_http_data_only: Optional[bool] = None, - collection_formats: Optional[Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: Optional[Union[int, float, Tuple]] = None, - _host: Optional[str] = None, - _check_type: Optional[bool] = None, - ): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :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 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 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 - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if async_threadpool_executor: - return self.threadpool_executor.submit( - 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, - ) - - if not async_req: - 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( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "HEAD": - 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( - 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( - 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( - 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( - 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( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - else: - raise PineconeApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." - ) diff --git a/pinecone/openapi_support/api_client_utils.py b/pinecone/openapi_support/api_client_utils.py deleted file mode 100644 index b6a736d36..000000000 --- a/pinecone/openapi_support/api_client_utils.py +++ /dev/null @@ -1,203 +0,0 @@ -import json -import mimetypes -import io -import os -from urllib3.fields import RequestField -from urllib.parse import quote - -from typing import Optional, List, Tuple, Dict, Any, Union -from .serializer import Serializer -from .exceptions import PineconeApiValueError - - -class HeaderUtil: - @staticmethod - def select_header_content_type(content_types: List[str]) -> str: - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return "application/json" - - content_types = [x.lower() for x in content_types] - - if "application/json" in content_types or "*/*" in content_types: - return "application/json" - else: - return content_types[0] - - @staticmethod - def select_header_accept(accepts: List[str]) -> str: - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return "" - - accepts = [x.lower() for x in accepts] - - if "application/json" in accepts: - return "application/json" - else: - return ", ".join(accepts) - - @staticmethod - def process_header_params( - default_headers: Dict[str, str], header_params: Dict[str, str], collection_formats - ) -> Dict[str, Any]: - header_params.update(default_headers) - if header_params: - sanitized_header_params: Dict[str, Any] = Serializer.sanitize_for_serialization( - header_params - ) - processed_header_params: Dict[str, Any] = dict( - parameters_to_tuples(sanitized_header_params, collection_formats) - ) - return processed_header_params - - @staticmethod - def prepare_headers(headers_map: Dict[str, List[str]], params) -> None: - """Mutates the params to set Accept and Content-Type headers.""" - accept_headers_list = headers_map["accept"] - if accept_headers_list: - params["header"]["Accept"] = HeaderUtil.select_header_accept(accept_headers_list) - - content_type_headers_list = headers_map["content_type"] - if content_type_headers_list: - header_list = HeaderUtil.select_header_content_type(content_type_headers_list) - params["header"]["Content-Type"] = header_list - - -def process_query_params(query_params, collection_formats): - if query_params: - sanitized_query_params = Serializer.sanitize_for_serialization(query_params) - processed_query_params = parameters_to_tuples(sanitized_query_params, collection_formats) - else: - processed_query_params = [] - - return processed_query_params - - -def process_params( - default_headers: Dict[str, str], - header_params: Dict[str, Any], - path_params: Dict[str, Any], - collection_formats: Dict[str, str], -): - # header parameters - headers_tuple = HeaderUtil.process_header_params( - default_headers, header_params, collection_formats - ) - - # path parameters - sanitized_path_params: Dict[str, Any] = Serializer.sanitize_for_serialization(path_params or {}) - path_parm: List[Tuple[str, Any]] = parameters_to_tuples( - sanitized_path_params, collection_formats - ) - - return headers_tuple, path_parm, sanitized_path_params - - -def parameters_to_multipart(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 - - -def files_parameters(files: Optional[Dict[str, List[io.IOBase]]] = 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 - """ - 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 - continue - if file_instance.closed is True: - raise PineconeApiValueError( - "Cannot read a closed file. The passed in file_type " - "for %s must be open." % param_name - ) - filename = os.path.basename(file_instance.name) # type: ignore - filedata = Serializer.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 - - -def parameters_to_tuples( - params: Union[Dict[str, Any], List[Tuple[str, Any]]], - collection_formats: Optional[Dict[str, str]], -) -> List[Tuple[str, str]]: - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params: List[Tuple[str, Any]] = [] - if collection_formats is None: - 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": - 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(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - -def build_request_url(config, processed_path_params, resource_path, _host): - for k, v in processed_path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # _host is a host override passed for an individual operation - host = _host if _host is not None else config.host - - return host + resource_path diff --git a/pinecone/openapi_support/api_version.py b/pinecone/openapi_support/api_version.py deleted file mode 100644 index fef29cbbd..000000000 --- a/pinecone/openapi_support/api_version.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is generated by codegen/build-oas.sh -# Do not edit this file manually. - -API_VERSION = "2025-01" -APIS_REPO_SHA = "eb79d8ea0c146aebe36c3769e19cbe9618db2d54" diff --git a/pinecone/openapi_support/asyncio_api_client.py b/pinecone/openapi_support/asyncio_api_client.py deleted file mode 100644 index 51f2e0ceb..000000000 --- a/pinecone/openapi_support/asyncio_api_client.py +++ /dev/null @@ -1,363 +0,0 @@ -import json -import io -from urllib3.fields import RequestField -import logging - -from typing import Optional, List, Tuple, Dict, Any, Union - - -from .rest_aiohttp import AiohttpRestClient -from .configuration import Configuration -from .exceptions import PineconeApiValueError, PineconeApiException -from .api_client_utils import ( - parameters_to_tuples, - files_parameters, - parameters_to_multipart, - process_params, - process_query_params, - build_request_url, -) -from .serializer import Serializer -from .deserializer import Deserializer -from .auth_util import AuthUtil - -logger = logging.getLogger(__name__) -""" @private """ - - -class AsyncioApiClient(object): - """Generic async API client for OpenAPI client library builds. - - :param configuration: .Configuration object for this client - """ - - def __init__(self, configuration=None, **kwargs) -> None: - if configuration is None: - configuration = Configuration.get_default_copy() - self.configuration = configuration - - self.rest_client = AiohttpRestClient(configuration) - - self.default_headers: Dict[str, str] = {} - # Set default User-Agent. - self.user_agent = "OpenAPI-Generator/1.0.0/python" - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_value, traceback): - await self.close() - - async def close(self): - logger.debug("Closing the aiohttp client") - await self.rest_client.close() - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers["User-Agent"] - - @user_agent.setter - def user_agent(self, value): - self.default_headers["User-Agent"] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - async def __call_api( - self, - resource_path: str, - method: str, - path_params: Optional[Dict[str, Any]] = None, - query_params: Optional[List[Tuple[str, Any]]] = None, - header_params: Optional[Dict[str, Any]] = None, - body: Optional[Any] = None, - post_params: Optional[List[Tuple[str, Any]]] = None, - files: Optional[Dict[str, List[io.IOBase]]] = None, - response_type: Optional[Tuple[Any]] = None, - auth_settings: Optional[List[str]] = None, - _return_http_data_only: Optional[bool] = None, - collection_formats: Optional[Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: Optional[Union[int, float, Tuple]] = None, - _host: Optional[str] = None, - _check_type: Optional[bool] = None, - ): - config = self.configuration - - path_params = path_params or {} - query_params = query_params or [] - header_params = header_params or {} - post_params = post_params or [] - files = files or {} - collection_formats = collection_formats or {} - - processed_header_params, processed_path_params, sanitized_path_params = process_params( - default_headers=self.default_headers, - header_params=header_params, - path_params=path_params, - collection_formats=collection_formats, - ) - - processed_query_params = process_query_params(query_params, collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - sanitized_post_params = Serializer.sanitize_for_serialization(post_params) - if sanitized_path_params: - processed_post_params = parameters_to_tuples( - sanitized_post_params, collection_formats - ) - processed_post_params.extend(files_parameters(files)) - if processed_header_params["Content-Type"].startswith("multipart"): - processed_post_params = parameters_to_multipart(sanitized_post_params, (dict)) - else: - processed_post_params = None - - # body - if body: - body = Serializer.sanitize_for_serialization(body) - - # auth setting - AuthUtil.update_params_for_auth( - configuration=self.configuration, - endpoint_auth_settings=auth_settings, - headers=processed_header_params, - querys=processed_query_params, - ) - - url = build_request_url( - config=config, - processed_path_params=processed_path_params, - resource_path=resource_path, - _host=_host, - ) - - try: - # perform request and return response - response_data = await self.request( - method, - url, - query_params=processed_query_params, - headers=processed_header_params, - post_params=processed_post_params, - body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - except PineconeApiException as e: - 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 - - # deserialize response data - if response_type: - Deserializer.decode_response(response_type=response_type, response=response_data) - return_data = Deserializer.deserialize( - response_data, response_type, self.configuration, _check_type - ) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return (return_data, response_data.status, response_data.getheaders()) - - 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 - - async def call_api( - self, - resource_path: str, - method: str, - path_params: Optional[Dict[str, Any]] = None, - query_params: Optional[List[Tuple[str, Any]]] = None, - header_params: Optional[Dict[str, Any]] = None, - body: Optional[Any] = None, - post_params: Optional[List[Tuple[str, Any]]] = None, - files: Optional[Dict[str, List[io.IOBase]]] = None, - response_type: Optional[Tuple[Any]] = None, - auth_settings: Optional[List[str]] = None, - _return_http_data_only: Optional[bool] = None, - collection_formats: Optional[Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: Optional[Union[int, float, Tuple]] = None, - _host: Optional[str] = None, - _check_type: Optional[bool] = None, - ): - """Makes the HTTP request (synchronous) and returns deserialized data. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :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 _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 _check_type: boolean describing if the data back from the server - should have its type checked. - :type _check_type: bool, optional - """ - return await 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, - ) - - async 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 await self.rest_client.GET( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "HEAD": - return await self.rest_client.HEAD( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "OPTIONS": - return await 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 await 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 await 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 await 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 await self.rest_client.DELETE( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - else: - raise PineconeApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data diff --git a/pinecone/openapi_support/asyncio_endpoint.py b/pinecone/openapi_support/asyncio_endpoint.py deleted file mode 100644 index d63a2d48d..000000000 --- a/pinecone/openapi_support/asyncio_endpoint.py +++ /dev/null @@ -1,149 +0,0 @@ -from .model_utils import none_type -from .api_client_utils import HeaderUtil -from .endpoint_utils import EndpointUtils, ExtraOpenApiKwargsTypedDict - - -class AsyncioEndpoint(object): - def __init__( - self, - settings=None, - params_map=None, - root_map=None, - headers_map=None, - api_client=None, - callable=None, - ) -> 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 (AsyncioApiClient) api client instance - callable (function): the function which is invoked when the - Endpoint is called - """ - self.settings = settings - self.params_map = params_map - self.params_map["all"].extend( - [ - "_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 = { - "_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 - - async def __call__(self, *args, **kwargs): - """This method is invoked when endpoints are called - Example: - - api_instance = InferenceApi() - api_instance.embed # this is an instance of the class Endpoint - api_instance.embed() # this invokes api_instance.embed.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.embed.callable or self.callable in this class - - """ - return await self.callable(self, *args, **kwargs) - - async def call_with_http_info(self, **kwargs): - _host = self.api_client.configuration.host - - EndpointUtils.raise_if_unexpected_param( - params_map=self.params_map, settings=self.settings, kwargs=kwargs - ) - - EndpointUtils.raise_if_missing_required_params( - params_map=self.params_map, settings=self.settings, kwargs=kwargs - ) - - EndpointUtils.raise_if_invalid_inputs( - config=self.api_client.configuration, - params_map=self.params_map, - allowed_values=self.allowed_values, - validations=self.validations, - openapi_types=self.openapi_types, - kwargs=kwargs, - ) - - params = EndpointUtils.gather_params( - attribute_map=self.attribute_map, - location_map=self.location_map, - openapi_types=self.openapi_types, - collection_format_map=self.collection_format_map, - kwargs=kwargs, - ) - - HeaderUtil.prepare_headers(headers_map=self.headers_map, params=params) - - return await 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"], - _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"], - ) - - def _process_openapi_kwargs( - self, kwargs: ExtraOpenApiKwargsTypedDict - ) -> ExtraOpenApiKwargsTypedDict: - 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) - return kwargs diff --git a/pinecone/openapi_support/auth_util.py b/pinecone/openapi_support/auth_util.py deleted file mode 100644 index 486935da0..000000000 --- a/pinecone/openapi_support/auth_util.py +++ /dev/null @@ -1,27 +0,0 @@ -from .exceptions import PineconeApiValueError - - -class AuthUtil: - @staticmethod - def update_params_for_auth(configuration, endpoint_auth_settings, headers, querys): - """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 auth_settings: Authentication setting identifiers list. - """ - if not endpoint_auth_settings: - return - - for auth in endpoint_auth_settings: - auth_setting = configuration.auth_settings().get(auth) - if auth_setting: - if 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 PineconeApiValueError( - "Authentication token must be in `query` or `header`" - ) diff --git a/pinecone/openapi_support/cached_class_property.py b/pinecone/openapi_support/cached_class_property.py deleted file mode 100644 index 157fdbd5d..000000000 --- a/pinecone/openapi_support/cached_class_property.py +++ /dev/null @@ -1,12 +0,0 @@ -class cached_class_property: - def __init__(self, func) -> None: - self.func = func - self.attr_name = f"__cached_{func.__name__}" - - def __get__(self, instance, owner): - # The value is stored on the owner (the class), not the instance. - if hasattr(owner, self.attr_name): - return getattr(owner, self.attr_name) - value = self.func(owner) - setattr(owner, self.attr_name, value) - return value diff --git a/pinecone/openapi_support/configuration.py b/pinecone/openapi_support/configuration.py deleted file mode 100644 index fb6d7d191..000000000 --- a/pinecone/openapi_support/configuration.py +++ /dev/null @@ -1,441 +0,0 @@ -import copy -import logging -import multiprocessing - -from http import client as http_client -from .exceptions import PineconeApiValueError -from typing import TypedDict - - -class HostSetting(TypedDict): - url: str - description: str - - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "maxItems", - "minItems", -} - - -class Configuration: - """Class to hold the configuration 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 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_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.openapi_support.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, - 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://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 - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - 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.openapi_support") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = "%(asctime)s %(levelname)s %(message)s" - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = ssl_ca_cert - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = "" - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - # Options to pass down to the underlying urllib3 socket - self.socket_options = None - - 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"): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - 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 PineconeApiValueError("Invalid keyword: '{0}''".format(v)) - self._disabled_client_side_validations = s - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = copy.deepcopy(default) - - @classmethod - def get_default_copy(cls): - """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 passed by the set_default method. - - :return: The configuration object. - """ - if cls._default is not None: - return copy.deepcopy(cls._default) - return Configuration() - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # 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 - 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 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :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"), - } - return auth - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [{"url": "https://api.pinecone.io", "description": "Production API endpoints"}] - - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path - - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. Must be less than {1}".format( - index, len(servers) - ) - ) - - 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"]) - - 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"] - ) - ) - - url = url.replace("{" + variable_name + "}", used_value) - - return url - - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None - - def __repr__(self): - attrs = [ - f"host={self.host}", - "api_key=***", - f"api_key_prefix={self.api_key_prefix}", - f"connection_pool_maxsize={self.connection_pool_maxsize}", - f"discard_unknown_keys={self.discard_unknown_keys}", - f"disabled_client_side_validations={self.disabled_client_side_validations}", - f"server_index={self.server_index}", - f"server_variables={self.server_variables}", - f"server_operation_index={self.server_operation_index}", - f"server_operation_variables={self.server_operation_variables}", - f"ssl_ca_cert={self.ssl_ca_cert}", - ] - return f"Configuration({', '.join(attrs)})" diff --git a/pinecone/openapi_support/constants.py b/pinecone/openapi_support/constants.py deleted file mode 100644 index b0c0464a8..000000000 --- a/pinecone/openapi_support/constants.py +++ /dev/null @@ -1,9 +0,0 @@ -OPENAPI_ENDPOINT_PARAMS = ( - "_return_http_data_only", - "_preload_content", - "_request_timeout", - "_check_input_type", - "_check_return_type", - "async_req", - "async_threadpool_executor", -) diff --git a/pinecone/openapi_support/deserializer.py b/pinecone/openapi_support/deserializer.py deleted file mode 100644 index 0fee3b941..000000000 --- a/pinecone/openapi_support/deserializer.py +++ /dev/null @@ -1,58 +0,0 @@ -import json -import re - -from .model_utils import deserialize_file, file_type, validate_and_convert_types - - -class Deserializer: - @staticmethod - def decode_response(response_type, response): - if response_type != (file_type,): - encoding = "utf-8" - content_type = response.getheader("content-type") - if content_type is not None and "charset=" in content_type: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - if match: - encoding = match.group(1) - response.data = response.data.decode(encoding) - - @staticmethod - def deserialize(response, response_type, config, _check_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 - - :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, config, content_disposition=content_disposition) - - # fetch data from response object - try: - received_data = json.loads(response.data) - except ValueError: - 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=config - ) - return deserialized_data diff --git a/pinecone/openapi_support/endpoint.py b/pinecone/openapi_support/endpoint.py deleted file mode 100644 index 9420fc2fd..000000000 --- a/pinecone/openapi_support/endpoint.py +++ /dev/null @@ -1,164 +0,0 @@ -from .model_utils import none_type -from typing import Dict, List, Callable -from .api_client import ApiClient -from .api_client_utils import HeaderUtil -from .endpoint_utils import ( - EndpointUtils, - EndpointParamsMapDict, - EndpointRootMapDict, - EndpointSettingsDict, - ExtraOpenApiKwargsTypedDict, -) - - -class Endpoint: - def __init__( - self, - settings: EndpointSettingsDict, - params_map: EndpointParamsMapDict, - root_map: EndpointRootMapDict, - headers_map: Dict[str, List[str]], - api_client: ApiClient, - callable: Callable, - ): - """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.settings = settings - self.params_map = params_map - self.params_map["all"].extend( - [ - "async_req", - "async_threadpool_executor", - "_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,), - "async_threadpool_executor": (bool,), - "_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 __call__(self, *args, **kwargs): - """This method is invoked when endpoints are called - Example: - - api_instance = InferenceApi() - api_instance.embed # this is an instance of the class Endpoint - api_instance.embed() # this invokes api_instance.embed.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.embed.callable or self.callable in this class - - """ - return self.callable(self, *args, **kwargs) - - def call_with_http_info(self, **kwargs): - _host = self.api_client.configuration.host - - EndpointUtils.raise_if_unexpected_param( - params_map=self.params_map, settings=self.settings, kwargs=kwargs - ) - - EndpointUtils.raise_if_missing_required_params( - params_map=self.params_map, settings=self.settings, kwargs=kwargs - ) - - EndpointUtils.raise_if_invalid_inputs( - config=self.api_client.configuration, - params_map=self.params_map, - allowed_values=self.allowed_values, - validations=self.validations, - openapi_types=self.openapi_types, - kwargs=kwargs, - ) - - params = EndpointUtils.gather_params( - attribute_map=self.attribute_map, - location_map=self.location_map, - openapi_types=self.openapi_types, - collection_format_map=self.collection_format_map, - kwargs=kwargs, - ) - - HeaderUtil.prepare_headers(headers_map=self.headers_map, params=params) - - return self.api_client.call_api( - self.settings["endpoint_path"], - self.settings["http_method"], - path_params=params["path"], - query_params=params["query"], - header_params=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"], - async_threadpool_executor=kwargs.get("async_threadpool_executor", None), - _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"], - ) - - def _process_openapi_kwargs( - self, kwargs: ExtraOpenApiKwargsTypedDict - ) -> ExtraOpenApiKwargsTypedDict: - 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) - return kwargs diff --git a/pinecone/openapi_support/endpoint_utils.py b/pinecone/openapi_support/endpoint_utils.py deleted file mode 100644 index 13522e854..000000000 --- a/pinecone/openapi_support/endpoint_utils.py +++ /dev/null @@ -1,185 +0,0 @@ -from .model_utils import file_type -from .exceptions import PineconeApiTypeError, PineconeApiValueError -from typing import Optional, Dict, Tuple, TypedDict, List, Literal, Any -from .types import PropertyValidationTypedDict -from .configuration import Configuration -from .model_utils import validate_and_convert_types, check_allowed_values, check_validations - - -class ExtraOpenApiKwargsTypedDict(TypedDict, total=False): - _return_http_data_only: Optional[bool] - _preload_content: Optional[bool] - _request_timeout: Optional[int] - _check_input_type: Optional[bool] - _check_return_type: Optional[bool] - async_req: Optional[bool] - - -class KwargsWithOpenApiKwargDefaultsTypedDict(TypedDict, total=False): - _return_http_data_only: bool - _preload_content: bool - _request_timeout: int - _check_input_type: bool - _check_return_type: bool - async_req: bool - - -class EndpointSettingsDict(TypedDict): - response_type: Optional[Tuple] - auth: List[str] - endpoint_path: str - operation_id: str - http_method: Literal["POST", "PUT", "PATCH", "GET", "DELETE"] - servers: Optional[List[str]] - - -class EndpointParamsMapDict(TypedDict): - all: List[str] - required: List[str] - nullable: List[str] - enum: List[str] - validation: List[str] - - -AllowedValuesDict = Dict[Tuple[str], Dict] - -AttributeMapDictType = Dict[str, str] -LocationMapDictType = Dict[str, str] -OpenapiTypesDictType = Dict[str, Tuple] - - -class EndpointRootMapDict(TypedDict): - validations: Dict[Tuple[str], PropertyValidationTypedDict] - allowed_values: Dict[Tuple[str], Dict] - openapi_types: OpenapiTypesDictType - attribute_map: AttributeMapDictType - location_map: LocationMapDictType - collection_format_map: Dict[str, str] - - -class CombinedParamsMapDict(TypedDict): - body: Any - collection_format: Dict[str, str] - file: Dict[str, List[file_type]] - form: List[Tuple[str, Any]] - header: Dict[str, List[str]] - path: Dict[str, Any] - query: List[Tuple[str, Any]] - - -class EndpointUtils: - @staticmethod - def gather_params( - attribute_map: AttributeMapDictType, - location_map: LocationMapDictType, - openapi_types: OpenapiTypesDictType, - collection_format_map: Dict[str, str], - kwargs: Dict[str, Any], - ) -> CombinedParamsMapDict: - params: CombinedParamsMapDict = { - "body": None, - "collection_format": {}, - "file": {}, - "form": [], - "header": {}, - "path": {}, - "query": [], - } - - for param_name, param_value in kwargs.items(): - param_location = 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 = attribute_map[param_name] - if param_location == "form" and openapi_types[param_name] == (file_type,): - params["file"][param_name] = [param_value] - elif param_location == "form" and openapi_types[param_name] == ([file_type],): - # param_value is already a list - params["file"][param_name] = param_value - elif param_location == "form": - param_value_full = (base_name, param_value) - params["form"].append(param_value_full) - elif param_location == "query": - param_value_full = (base_name, param_value) - params["query"].append(param_value_full) - elif param_location == "header": - params["header"][base_name] = param_value - elif param_location == "path": - params["path"][base_name] = param_value - else: - raise PineconeApiTypeError("Got an unexpected location '%s' for parameter `%s`") - - collection_format = collection_format_map.get(param_name) - if collection_format: - params["collection_format"][base_name] = collection_format - - return params - - @staticmethod - def raise_if_missing_required_params( - params_map: EndpointParamsMapDict, settings: EndpointSettingsDict, kwargs: Dict[str, Any] - ) -> None: - for key in params_map["required"]: - if key not in kwargs.keys(): - raise PineconeApiValueError( - "Missing the required parameter `%s` when calling " - "`%s`" % (key, settings["operation_id"]) - ) - - @staticmethod - def raise_if_unexpected_param( - params_map: EndpointParamsMapDict, settings: EndpointSettingsDict, kwargs: Dict[str, Any] - ) -> None: - for key, value in kwargs.items(): - if key not in params_map["all"]: - raise PineconeApiTypeError( - "Got an unexpected parameter '%s'" - " to method `%s`" % (key, settings["operation_id"]) - ) - # 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 params_map["nullable"] - and value is None - and kwargs["_check_input_type"] is False - ): - raise PineconeApiValueError( - "Value may not be None for non-nullable parameter `%s`" - " when calling `%s`" % (key, settings["operation_id"]) - ) - - @staticmethod - def raise_if_invalid_inputs( - config: Configuration, - params_map: EndpointParamsMapDict, - allowed_values: AllowedValuesDict, - validations: PropertyValidationTypedDict, - openapi_types: OpenapiTypesDictType, - kwargs: Dict[str, Any], - ) -> None: - for param in params_map["enum"]: - if param in kwargs: - check_allowed_values(allowed_values, (param,), kwargs[param]) - - for param in params_map["validation"]: - if param in kwargs: - check_validations(validations, (param,), kwargs[param], configuration=config) - - if kwargs["_check_input_type"] is False: - return - - for key, value in kwargs.items(): - fixed_val = validate_and_convert_types( - value, - openapi_types[key], - [key], - False, - kwargs["_check_input_type"], - configuration=config, - ) - kwargs[key] = fixed_val diff --git a/pinecone/openapi_support/exceptions.py b/pinecone/openapi_support/exceptions.py deleted file mode 100644 index fcc37da33..000000000 --- a/pinecone/openapi_support/exceptions.py +++ /dev/null @@ -1,140 +0,0 @@ -class PineconeException(Exception): - """The base exception class for all exceptions in the Pinecone Python SDK""" - - -class PineconeApiTypeError(PineconeException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> None: - """Raises an exception for TypeErrors - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - 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 - None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(PineconeApiTypeError, self).__init__(full_msg) - - -class PineconeApiValueError(PineconeException, ValueError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ - - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(PineconeApiValueError, self).__init__(full_msg) - - -class PineconeApiAttributeError(PineconeException, AttributeError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Raised when an attribute reference or assignment fails. - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(PineconeApiAttributeError, self).__init__(full_msg) - - -class PineconeApiKeyError(PineconeException, KeyError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(PineconeApiKeyError, self).__init__(full_msg) - - -class PineconeApiException(PineconeException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\nReason: {1}\n".format(self.status, self.reason) - if 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) - - return error_message - - -class NotFoundException(PineconeApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(PineconeApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(PineconeApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(PineconeApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) - - -def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, int): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result diff --git a/pinecone/openapi_support/model_utils.py b/pinecone/openapi_support/model_utils.py deleted file mode 100644 index 4fc4cf0fe..000000000 --- a/pinecone/openapi_support/model_utils.py +++ /dev/null @@ -1,1928 +0,0 @@ -from datetime import date, datetime # noqa: F401 -from dateutil.parser import parse - -import inspect -import io -import os -import pprint -import re -import tempfile - -from .exceptions import ( - PineconeApiKeyError, - PineconeApiAttributeError, - PineconeApiTypeError, - PineconeApiValueError, -) - -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) -> None: - 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, 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 PineconeApiAttributeError( - "{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) is not str: - error_msg = type_error_message( - var_name=name, var_value=name, valid_classes=(str,), key_type=True - ) - raise PineconeApiTypeError( - 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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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) # noqa: F841 - - 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 PineconeApiAttributeError( - "{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 PineconeApiAttributeError( - "{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 PineconeApiAttributeError( - "{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 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__), - [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 PineconeApiAttributeError( - "{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 input_value is None: - 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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError( - "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 PineconeApiValueError(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 PineconeApiValueError("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 PineconeApiTypeError( - 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 - """ - 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 is 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( - "{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: - PineconeApiTypeError - PineconeApiValueError - PineconeApiKeyError - """ - - 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: - PineconeApiTypeError - PineconeApiValueError - PineconeApiKeyError - """ - 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 (PineconeApiTypeError, PineconeApiValueError, PineconeApiKeyError) 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: - PineconeApiTypeError - """ - 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) is not 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 hasattr(model_instance, "_composed_schemas") and 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 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" - % (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, 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 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 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__ - ) - 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 PineconeApiValueError( - "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/openapi_support/rest_aiohttp.py b/pinecone/openapi_support/rest_aiohttp.py deleted file mode 100644 index c7121a11f..000000000 --- a/pinecone/openapi_support/rest_aiohttp.py +++ /dev/null @@ -1,193 +0,0 @@ -import ssl -import certifi -import json -from .rest_utils import RestClientInterface, RESTResponse, raise_exceptions_or_return -from .configuration import Configuration - - -class AiohttpRestClient(RestClientInterface): - def __init__(self, configuration: Configuration) -> None: - try: - import aiohttp - except ImportError: - raise ImportError( - "Additional dependencies are required to use Pinecone with asyncio. Include these extra dependencies in your project by installing `pinecone[asyncio]`." - ) from None - - if configuration.ssl_ca_cert is not None: - ca_certs = configuration.ssl_ca_cert - else: - ca_certs = certifi.where() - - ssl_context = ssl.create_default_context(cafile=ca_certs) - - conn = aiohttp.TCPConnector(verify_ssl=configuration.verify_ssl, ssl=ssl_context) - - if configuration.proxy: - self._session = aiohttp.ClientSession(connector=conn, proxy=configuration.proxy) - else: - self._session = aiohttp.ClientSession(connector=conn) - - async def close(self): - await self._session.close() - - async def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - if method in ["POST", "PUT", "PATCH", "OPTIONS"] and ("Content-Type" not in headers): - headers["Content-Type"] = "application/json" - - if "application/x-ndjson" in headers.get("Content-Type", "").lower(): - ndjson_data = "\n".join(json.dumps(record) for record in body) - - async with self._session.request( - method, url, params=query_params, headers=headers, data=ndjson_data - ) as resp: - content = await resp.read() - return raise_exceptions_or_return( - RESTResponse(resp.status, content, resp.headers, resp.reason) - ) - - else: - async with self._session.request( - method, url, params=query_params, headers=headers, json=body - ) as resp: - content = await resp.read() - return raise_exceptions_or_return( - RESTResponse(resp.status, content, resp.headers, resp.reason) - ) - - async def GET( - self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None - ): - return await self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - async def HEAD( - self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None - ): - return await self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - async def OPTIONS( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return await self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - async def DELETE( - self, - url, - headers=None, - query_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return await self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - async def POST( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return await self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - async def PUT( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return await self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - async def PATCH( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return await 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/openapi_support/rest_urllib3.py b/pinecone/openapi_support/rest_urllib3.py deleted file mode 100644 index 85d008dad..000000000 --- a/pinecone/openapi_support/rest_urllib3.py +++ /dev/null @@ -1,260 +0,0 @@ -import json -import logging -import ssl -import os -from typing import Optional -from urllib.parse import urlencode, quote -from .configuration import Configuration -from .rest_utils import raise_exceptions_or_return, RESTResponse, RestClientInterface - -import urllib3 - -from .exceptions import PineconeApiException, PineconeApiValueError - - -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__) -""" @private """ - - -class Urllib3RestClient(RestClientInterface): - pool_manager: urllib3.PoolManager - - def __init__( - self, configuration: Configuration, pools_size: int = 4, maxsize: Optional[int] = 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 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args["assert_hostname"] = configuration.assert_hostname # noqa: E501 - - if configuration.retries is not None: - addition_pool_args["retries"] = configuration.retries - - if configuration.socket_options is not None: - addition_pool_args["socket_options"] = configuration.socket_options - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args, - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args, - ) - - 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 - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :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. - """ - logger.debug("Calling urllib3 request()") - method = method.upper() - 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 PineconeApiValueError("body parameter cannot be used with post_params parameter.") - - post_params = post_params or {} - headers = headers or {} - - 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]) - - 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, quote_via=quote) - - content_type = headers.get("Content-Type", "").lower() - if content_type == "" or ("json" in content_type): - if body is None: - request_body = None - else: - if content_type == "application/x-ndjson": - # for x-ndjson requests, we are expecting an array of elements - # that need to be converted to a newline separated string - request_body = "\n".join(json.dumps(element) for element in body) - else: # content_type == "application/json": - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - - elif content_type == "application/x-www-form-urlencoded": # noqa: E501 - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif 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"] - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - 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, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise PineconeApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - if query_params: - url += "?" + urlencode(query_params, quote_via=quote) - r = self.pool_manager.request( - method, url, 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 PineconeApiException(status=0, reason=msg) - - if os.environ.get("PINECONE_DEBUG_CURL"): - o = RESTResponse(r.status, r.data, r.headers, r.reason) - - if o.status <= 300: - print(bcolors.OKGREEN + o.data.decode("utf-8") + bcolors.ENDC) - else: - print(bcolors.FAIL + o.data.decode("utf-8") + bcolors.ENDC) - - if _preload_content: - r = RESTResponse(r.status, r.data, r.headers, r.reason) - - # log response body - logger.debug("response body: %s", r.data) - - return raise_exceptions_or_return(r) diff --git a/pinecone/openapi_support/rest_utils.py b/pinecone/openapi_support/rest_utils.py deleted file mode 100644 index 77bb4c374..000000000 --- a/pinecone/openapi_support/rest_utils.py +++ /dev/null @@ -1,197 +0,0 @@ -import io -from abc import ABC, abstractmethod -import logging - -from .exceptions import ( - PineconeApiException, - UnauthorizedException, - ForbiddenException, - NotFoundException, - ServiceException, -) - -logger = logging.getLogger(__name__) -""" @private """ - - -class RESTResponse(io.IOBase): - def __init__(self, status, data, headers, reason=None) -> None: - self.status = status - self.reason = reason - self.data = data - self.headers = headers - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.headers.get(name, default) - - -def raise_exceptions_or_return(r: RESTResponse): - logger.debug("response status: %s", r.status) - - if not 200 <= r.status <= 299: - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise PineconeApiException(http_resp=r) - - return r - - -class RestClientInterface(ABC): - def __init__(self, configuration, **kwargs) -> None: - pass - - @abstractmethod - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - pass - - 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/openapi_support/serializer.py b/pinecone/openapi_support/serializer.py deleted file mode 100644 index fa59396ae..000000000 --- a/pinecone/openapi_support/serializer.py +++ /dev/null @@ -1,50 +0,0 @@ -import io - -from typing import Any - - -from .exceptions import PineconeApiValueError -from .model_utils import ModelNormal, ModelSimple, ModelComposed, date, datetime, model_to_dict - - -class Serializer: - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data - - @classmethod - def sanitize_for_serialization(cls, obj) -> Any: - """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 - convert to string in iso8601 format. - 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, bool)) or obj is None: - return obj - 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): - return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} - raise PineconeApiValueError( - "Unable to prepare type {} for serialization".format(obj.__class__.__name__) - ) diff --git a/pinecone/openapi_support/types.py b/pinecone/openapi_support/types.py deleted file mode 100644 index 883885b3e..000000000 --- a/pinecone/openapi_support/types.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import TypedDict, Dict, Union - - -class PropertyValidationTypedDict(TypedDict, total=False): - max_length: int - min_length: int - max_items: int - min_items: int - exclusive_maximum: Union[int, float] - inclusive_maximum: Union[int, float] - exclusive_minimum: Union[int, float] - inclusive_minimum: Union[int, float] - regex: Dict[str, str] - multiple_of: int diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py deleted file mode 100644 index 3d72b5d64..000000000 --- a/pinecone/utils/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -from .check_kwargs import check_kwargs -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 -from .convert_to_list import convert_to_list -from .convert_enum_to_string import convert_enum_to_string -from .normalize_host import normalize_host -from .setup_openapi_client import ( - setup_openapi_client, - build_plugin_setup_client, - setup_async_openapi_client, -) -from .parse_args import parse_non_empty_args -from .docslinks import docslinks -from .repr_overrides import install_json_repr_override -from .error_handling import validate_and_convert_errors -from .plugin_aware import PluginAware -from .filter_dict import filter_dict - -__all__ = [ - "PluginAware", - "check_kwargs", - "__version__", - "get_user_agent", - "warn_deprecated", - "fix_tuple_length", - "convert_to_list", - "normalize_host", - "setup_openapi_client", - "setup_async_openapi_client", - "build_plugin_setup_client", - "parse_non_empty_args", - "docslinks", - "install_json_repr_override", - "validate_and_convert_errors", - "convert_enum_to_string", - "filter_dict", -] diff --git a/pinecone/utils/check_kwargs.py b/pinecone/utils/check_kwargs.py deleted file mode 100644 index 17038b1ec..000000000 --- a/pinecone/utils/check_kwargs.py +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index b58d0b217..000000000 --- a/pinecone/utils/constants.py +++ /dev/null @@ -1,17 +0,0 @@ -import os - -from .version import __version__ - -MAX_MSG_SIZE = 128 * 1024 * 1024 - -MAX_ID_LENGTH = int(os.getenv("PINECONE_MAX_ID_LENGTH", default="64")) - -REQUEST_ID: str = "request_id" - -CLIENT_VERSION = __version__ -CLIENT_ID = f"python-client-{CLIENT_VERSION}" - -REQUIRED_VECTOR_FIELDS = {"id"} -OPTIONAL_VECTOR_FIELDS = {"values", "sparse_values", "metadata"} - -SOURCE_TAG = "source_tag" diff --git a/pinecone/utils/convert_enum_to_string.py b/pinecone/utils/convert_enum_to_string.py deleted file mode 100644 index 16fb9d849..000000000 --- a/pinecone/utils/convert_enum_to_string.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Union -from enum import Enum - - -def convert_enum_to_string(value: Union[Enum, str]) -> str: - if isinstance(value, Enum): - return str(value.value) - return value diff --git a/pinecone/utils/convert_to_list.py b/pinecone/utils/convert_to_list.py deleted file mode 100644 index 6898b029d..000000000 --- a/pinecone/utils/convert_to_list.py +++ /dev/null @@ -1,23 +0,0 @@ -from ..exceptions.exceptions import ListConversionException - - -def convert_to_list(obj): - class_name = obj.__class__.__name__ - - if class_name == "list": - return obj - elif hasattr(obj, "tolist") and callable(getattr(obj, "tolist")): - return obj.tolist() - elif obj is None or isinstance(obj, str) or isinstance(obj, dict): - # The string and dictionary classes in python can be passed to list() - # but they're not going to yield sensible results for our use case. - raise ListConversionException( - f"Expected a list or list-like data structure, but got: {obj}" - ) - else: - try: - return list(obj) - except Exception as e: - raise ListConversionException( - f"Expected a list or list-like data structure, but got: {obj}" - ) from e diff --git a/pinecone/utils/deprecation_notice.py b/pinecone/utils/deprecation_notice.py deleted file mode 100644 index 03bc08375..000000000 --- a/pinecone/utils/deprecation_notice.py +++ /dev/null @@ -1,6 +0,0 @@ -import warnings - - -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) diff --git a/pinecone/utils/docslinks.py b/pinecone/utils/docslinks.py deleted file mode 100644 index a86dd1da7..000000000 --- a/pinecone/utils/docslinks.py +++ /dev/null @@ -1,10 +0,0 @@ -from pinecone.core.openapi.db_control import API_VERSION - -docslinks = { - "README": "https://github.com/pinecone-io/pinecone-python-client/blob/main/README.md", - "GITHUB_REPO": "https://github.com/pinecone-io/pinecone-python-client", - "LANGCHAIN_IMPORT_KB_ARTICLE": "https://docs.pinecone.io/troubleshooting/pinecone-attribute-errors-with-langchain", - "API_DESCRIBE_INDEX": "https://docs.pinecone.io/reference/api/{}/control-plane/describe_index".format( - API_VERSION - ), -} diff --git a/pinecone/utils/error_handling.py b/pinecone/utils/error_handling.py deleted file mode 100644 index 5cdaaaf46..000000000 --- a/pinecone/utils/error_handling.py +++ /dev/null @@ -1,25 +0,0 @@ -import inspect -from functools import wraps - -from urllib3.exceptions import MaxRetryError, ProtocolError - - -def validate_and_convert_errors(func): - @wraps(func) - def inner_func(*args, **kwargs): - 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 - else: - raise - except ProtocolError as e: - raise ProtocolError("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 diff --git a/pinecone/utils/filter_dict.py b/pinecone/utils/filter_dict.py deleted file mode 100644 index 579563408..000000000 --- a/pinecone/utils/filter_dict.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Tuple, Dict - - -def filter_dict(d: Dict, allowed_keys: Tuple[str, ...]) -> Dict: - return {k: v for k, v in d.items() if k in allowed_keys} diff --git a/pinecone/utils/fix_tuple_length.py b/pinecone/utils/fix_tuple_length.py deleted file mode 100644 index 127629869..000000000 --- a/pinecone/utils/fix_tuple_length.py +++ /dev/null @@ -1,3 +0,0 @@ -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 diff --git a/pinecone/utils/normalize_host.py b/pinecone/utils/normalize_host.py deleted file mode 100644 index 01ee09d3a..000000000 --- a/pinecone/utils/normalize_host.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Optional - - -def normalize_host(host: Optional[str]) -> str: - if host is None: - return "" - if host.startswith("https://"): - return host - if host.startswith("http://"): - return host - return "https://" + host diff --git a/pinecone/utils/parse_args.py b/pinecone/utils/parse_args.py deleted file mode 100644 index afac0c712..000000000 --- a/pinecone/utils/parse_args.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import List, Tuple, Any, Dict - - -def parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: - return {arg_name: val for arg_name, val in args if val is not None} diff --git a/pinecone/utils/plugin_aware.py b/pinecone/utils/plugin_aware.py deleted file mode 100644 index ce1e4b87e..000000000 --- a/pinecone/utils/plugin_aware.py +++ /dev/null @@ -1,27 +0,0 @@ -from .setup_openapi_client import build_plugin_setup_client -from pinecone.config import Config -from pinecone.openapi_support.configuration import Configuration as OpenApiConfig - - -from pinecone_plugin_interface import load_and_install as install_plugins -import logging - -logger = logging.getLogger(__name__) -""" @private """ - - -class PluginAware: - def load_plugins( - self, config: Config, openapi_config: OpenApiConfig, pool_threads: int - ) -> None: - """@private""" - try: - # I don't expect this to ever throw, but wrapping this in a - # try block just in case to make sure a bad plugin doesn't - # halt client initialization. - openapi_client_builder = build_plugin_setup_client( - config=config, openapi_config=openapi_config, pool_threads=pool_threads - ) - install_plugins(self, openapi_client_builder) - except Exception as e: - logger.error(f"Error loading plugins: {e}") diff --git a/pinecone/utils/repr_overrides.py b/pinecone/utils/repr_overrides.py deleted file mode 100644 index e3dfdb667..000000000 --- a/pinecone/utils/repr_overrides.py +++ /dev/null @@ -1,15 +0,0 @@ -import json -from datetime import datetime - - -def custom_serializer(obj): - if isinstance(obj, datetime): - return obj.isoformat() - else: - return str(obj) - - -def install_json_repr_override(klass): - klass.__repr__ = lambda self: json.dumps( - self.to_dict(), indent=4, sort_keys=False, default=custom_serializer - ) diff --git a/pinecone/utils/setup_openapi_client.py b/pinecone/utils/setup_openapi_client.py deleted file mode 100644 index 1c2015eb8..000000000 --- a/pinecone/utils/setup_openapi_client.py +++ /dev/null @@ -1,56 +0,0 @@ -from .user_agent import get_user_agent -import copy - - -def setup_async_openapi_client( - api_client_klass, api_klass, config, openapi_config, api_version=None, **kwargs -): - if kwargs.get("host"): - openapi_config = copy.deepcopy(openapi_config) - openapi_config._base_path = kwargs["host"] - - api_client = api_client_klass(configuration=openapi_config) - api_client.user_agent = get_user_agent(config) - extra_headers = config.additional_headers or {} - for key, value in extra_headers.items(): - api_client.set_default_header(key, value) - - if api_version: - api_client.set_default_header("X-Pinecone-API-Version", api_version) - client = api_klass(api_client) - return client - - -def setup_openapi_client( - api_client_klass, api_klass, config, openapi_config, pool_threads, api_version=None, **kwargs -): - # It is important that we allow the user to pass in a reference to api_client_klass - # instead of creating a direct dependency on ApiClient because plugins have their - # own ApiClient implementations. Even if those implementations seem like they should - # be functionally identical, they are not the same class and have references to - # different copies of the ModelNormal class. Therefore cannot be used interchangeably. - # without breaking the generated client code anywhere it is relying on isinstance to make - # a decision about something. - if kwargs.get("host"): - openapi_config = copy.deepcopy(openapi_config) - openapi_config._base_path = kwargs["host"] - - api_client = api_client_klass(configuration=openapi_config, pool_threads=pool_threads) - api_client.user_agent = get_user_agent(config) - extra_headers = config.additional_headers or {} - for key, value in extra_headers.items(): - api_client.set_default_header(key, value) - - if api_version: - api_client.set_default_header("X-Pinecone-API-Version", api_version) - client = api_klass(api_client) - return client - - -def build_plugin_setup_client(config, openapi_config, pool_threads): - def setup_plugin_client(api_client_klass, api_klass, api_version, **kwargs): - return setup_openapi_client( - api_client_klass, api_klass, config, openapi_config, pool_threads, api_version, **kwargs - ) - - return setup_plugin_client diff --git a/pinecone/utils/tqdm.py b/pinecone/utils/tqdm.py deleted file mode 100644 index 059076860..000000000 --- a/pinecone/utils/tqdm.py +++ /dev/null @@ -1,28 +0,0 @@ -try: - # Use the notebook-friendly auto selection if tqdm is installed. - from tqdm.auto import tqdm -except ImportError: - # Fallback: define a dummy tqdm that supports the same interface. - class tqdm: # type: ignore - def __init__(self, iterable=None, total=None, desc="", **kwargs): - self.iterable = iterable - self.total = total - self.desc = desc - # You can store additional kwargs if needed - - def __iter__(self): - # Just iterate over the underlying iterable - for item in self.iterable: - yield item - - def update(self, n=1): - # No-op: This stub doesn't track progress - pass - - def __enter__(self): - # Allow use as a context manager - return self - - def __exit__(self, exc_type, exc_value, traceback): - # Nothing to cleanup - pass diff --git a/pinecone/utils/user_agent.py b/pinecone/utils/user_agent.py deleted file mode 100644 index 845a0ab1f..000000000 --- a/pinecone/utils/user_agent.py +++ /dev/null @@ -1,35 +0,0 @@ -import urllib3 - -from .version import __version__ -from .constants import SOURCE_TAG -import re - - -def _build_source_tag_field(source_tag): - # normalize source tag - # 1. Lowercase - # 2. Limit charset to [a-z0-9_ :] - # 3. Trim left/right whitespace - # 4. Condense multiple spaces to one, and replace with underscore - tag = source_tag.lower() - tag = re.sub(r"[^a-z0-9_ :]", "", tag) - tag = tag.strip() - tag = "_".join(tag.split()) - return f"{SOURCE_TAG}={tag}" - - -def _get_user_agent(client_id, config): - user_agent_details = {"urllib3": urllib3.__version__} - user_agent = "{} ({})".format( - client_id, ", ".join([f"{k}:{v}" for k, v in user_agent_details.items()]) - ) - user_agent += f"; {_build_source_tag_field(config.source_tag)}" if config.source_tag else "" - return user_agent - - -def get_user_agent(config): - return _get_user_agent(f"python-client-{__version__}", config) - - -def get_user_agent_grpc(config): - return _get_user_agent(f"python-client[grpc]-{__version__}", config) diff --git a/pinecone/utils/version.py b/pinecone/utils/version.py deleted file mode 100644 index 1da30cfe4..000000000 --- a/pinecone/utils/version.py +++ /dev/null @@ -1,8 +0,0 @@ -from pathlib import Path - - -def get_version(): - return Path(__file__).parent.parent.joinpath("__version__").read_text().strip() - - -__version__ = get_version() diff --git a/pyproject.toml b/pyproject.toml index 7f01dc77b..3ffc1786b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,10 @@ [tool.poetry] -name = "pinecone" -version = "6.0.1" +name = "pinecone-client" +version = "5.9.9" packages = [ { include="pinecone", from="." }, ] -description = "Pinecone client and SDK" +description = "Pinecone client (DEPRECATED)" authors = ["Pinecone Systems, Inc. "] license = "Apache-2.0" readme = "README.md" From 2e67c48e8927f83323f7e73cc812c5bd2441f0ae Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 13:29:46 -0500 Subject: [PATCH 2/8] Adjust message --- pinecone/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pinecone/__init__.py b/pinecone/__init__.py index dcc73b8f7..31873474a 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -3,5 +3,5 @@ """ raise Exception( - "The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please update your projects to use the `pinecone` package name. See the README at https://github.com/pinecone-io/pinecone-python-client for more information." + "The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please remove `pinecone-client` from your project dependencies and add `pinecone` instead. See the README at https://github.com/pinecone-io/pinecone-python-client for more information on using the python SDK." ) From 867bdb6b5a60def23155084aaed5ef7aeeb25cc2 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 14:03:08 -0500 Subject: [PATCH 3/8] Adjust readme --- README.md | 4 ++-- pinecone/__version__ | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61ac0454b..34ae7972b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Pinecone Python Client (DEPRECATED) -The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please update your projects to consume future updates using the `pinecone` package name. +The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please remove `pinecone-client` from your project dependencies and add the `pinecone` package to get the latest updates. -- [`pinecone`](https://pypi.org/project/pinecone/) on PyPI +- `pinecone` on [PyPI](https://pypi.org/project/pinecone/) - [Source on Github](https://github.com/pinecone-io/pinecone-python-client) diff --git a/pinecone/__version__ b/pinecone/__version__ index 6d54bbd77..457a67e52 100644 --- a/pinecone/__version__ +++ b/pinecone/__version__ @@ -1 +1 @@ -6.0.1 \ No newline at end of file +5.9.9 From 11c0060e848332cb840c931201525f3ddc93a822 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 14:04:50 -0500 Subject: [PATCH 4/8] Adjust README --- .github/workflows/release.yaml | 36 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 6889c4840..43af0a01b 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,22 +19,22 @@ on: - 'major' # breaking changes jobs: - unit-tests: - uses: './.github/workflows/testing-unit.yaml' - secrets: inherit - integration-tests: - uses: './.github/workflows/testing-integration.yaml' - secrets: inherit - dependency-tests: - uses: './.github/workflows/testing-dependency.yaml' - secrets: inherit + # unit-tests: + # uses: './.github/workflows/testing-unit.yaml' + # secrets: inherit + # integration-tests: + # uses: './.github/workflows/testing-integration.yaml' + # secrets: inherit + # dependency-tests: + # uses: './.github/workflows/testing-dependency.yaml' + # secrets: inherit pypi: uses: './.github/workflows/publish-to-pypi.yaml' - needs: - - unit-tests - - integration-tests - - dependency-tests + # needs: + # - unit-tests + # - integration-tests + # - dependency-tests with: isPrerelease: false ref: ${{ inputs.ref }} @@ -45,8 +45,8 @@ jobs: PYPI_USERNAME: __token__ PYPI_PASSWORD: ${{ secrets.PROD_PYPI_PUBLISH_TOKEN }} - docs-publish: - uses: './.github/workflows/build-and-publish-docs.yaml' - secrets: inherit - needs: - - pypi + # docs-publish: + # uses: './.github/workflows/build-and-publish-docs.yaml' + # secrets: inherit + # needs: + # - pypi From 26505767ebf15022b12eb0a26583036bade36846 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 14:18:56 -0500 Subject: [PATCH 5/8] Add more info to README --- README.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 34ae7972b..33925a69c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,26 @@ # Pinecone Python Client (DEPRECATED) -The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. Please remove `pinecone-client` from your project dependencies and add the `pinecone` package to get the latest updates. +The official Pinecone python package has been renamed from `pinecone-client` to `pinecone`. To upgrade, please +**remove** `pinecone-client` from your project dependencies and then **add** the `pinecone` package to get the +latest updates. + +> [!WARNING] +> Failure to remove `pinecone-client` before installing `pinecone` can lead to confusing interactions +> between the two packages. + +```sh +pip uninstall pinecone-client +pip install pinecone +``` + +Or, if you are using grpc: + +```sh +pip uninstall pinecone-client +pip install "pinecone[grpc]" +``` + +## Links - `pinecone` on [PyPI](https://pypi.org/project/pinecone/) - [Source on Github](https://github.com/pinecone-io/pinecone-python-client) From e6988aa54332919556a48fbd23cfc734c3407f0d Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 14:31:21 -0500 Subject: [PATCH 6/8] Adjust readme --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 33925a69c..cd26e28a2 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,11 @@ The official Pinecone python package has been renamed from `pinecone-client` to **remove** `pinecone-client` from your project dependencies and then **add** the `pinecone` package to get the latest updates. -> [!WARNING] -> Failure to remove `pinecone-client` before installing `pinecone` can lead to confusing interactions -> between the two packages. + +**WARNING:** Failure to remove `pinecone-client` before installing `pinecone` can lead to confusing interactions +between the two packages. + +## Upgrade steps ```sh pip uninstall pinecone-client @@ -20,6 +22,8 @@ pip uninstall pinecone-client pip install "pinecone[grpc]" ``` +For info on code changes that may impact you, see [Release Notes](https://github.com/pinecone-io/pinecone-python-client/releases) and [Upgrading](https://github.com/pinecone-io/pinecone-python-client/blob/main/docs/upgrading.md) + ## Links - `pinecone` on [PyPI](https://pypi.org/project/pinecone/) From 7d14c23a49727140680d3caa995383fcfc9c6dfb Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Fri, 21 Feb 2025 14:35:30 -0500 Subject: [PATCH 7/8] Adjust tagging --- .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 3e5e80d86..5d2b69ec2 100644 --- a/.github/workflows/publish-to-pypi.yaml +++ b/.github/workflows/publish-to-pypi.yaml @@ -121,7 +121,7 @@ jobs: - name: Tag version run: | - newVersionTag="${{ steps.bump.outputs.VERSION_TAG }}" + newVersionTag="pinecone-client-${{ steps.bump.outputs.VERSION_TAG }}" git tag -a $newVersionTag -m "Release $newVersionTag" - name: Push tags (prerelease) From 8f40d4db2ce37d3dd54fa092abc64c7ce0a8585c Mon Sep 17 00:00:00 2001 From: Pinecone CI Date: Fri, 21 Feb 2025 19:47:41 +0000 Subject: [PATCH 8/8] [skip ci] Bump version to v6.0.0 --- pinecone/__version__ | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pinecone/__version__ b/pinecone/__version__ index 457a67e52..f4965a313 100644 --- a/pinecone/__version__ +++ b/pinecone/__version__ @@ -1 +1 @@ -5.9.9 +6.0.0 \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 3ffc1786b..82810ea73 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "pinecone-client" -version = "5.9.9" +version = "6.0.0" packages = [ { include="pinecone", from="." }, ]