From 035248d51f436760abd0b6c88522e47df96598b5 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 24 Jun 2024 15:13:24 -0400 Subject: [PATCH 01/13] Add codegen script --- .gitmodules | 6 +++ codegen/apis | 1 + codegen/build-oas.sh | 86 ++++++++++++++++++++++++++++++++++++ codegen/openapi-config.json | 4 ++ codegen/python-oas-templates | 1 + 5 files changed, 98 insertions(+) create mode 100644 .gitmodules create mode 160000 codegen/apis create mode 100755 codegen/build-oas.sh create mode 100644 codegen/openapi-config.json create mode 160000 codegen/python-oas-templates diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..e6d37dc4b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "codegen/apis"] + path = codegen/apis + url = git@github.com:pinecone-io/apis.git +[submodule "codegen/python-oas-templates"] + path = codegen/python-oas-templates + url = git@github.com:pinecone-io/python-oas-templates.git diff --git a/codegen/apis b/codegen/apis new file mode 160000 index 000000000..94edff09f --- /dev/null +++ b/codegen/apis @@ -0,0 +1 @@ +Subproject commit 94edff09fa52e8a0c800602798b3fba36f7465b8 diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh new file mode 100755 index 000000000..e9c0028a9 --- /dev/null +++ b/codegen/build-oas.sh @@ -0,0 +1,86 @@ +#!/bin/bash + +version='2024-04' + +rm -rf build +mkdir build + +# pushd codegen/apis +# just build +# popd + +verify_spec_version() { + local version=$1 + if [ -z "$version" ]; then + echo "Version is required" + exit 1 + fi + + if [ ! -d "codegen/apis/static/$version" ]; then + echo "Version $version does not exist in static dir" + exit 1 + fi +} + +verify_spec_file_exists() { + local oas_file=$1 + if [ ! -f "$oas_file" ]; then + echo "Spec file does not exist at $oas_file" + exit 1 + fi +} + +generate_client() { + local oas_file=$1 + local template_dir="codegen/python-oas-templates/templates5.2.0" + + if [ ! -f "$oas_file" ]; then + echo "Spec file does not exist at $oas_file" + exit 1 + fi + if [ ! -d "$template_dir" ]; then + echo "Template directory does not exist at $template_dir" + exit 1 + fi + + # Cleanup previous build files + echo "Cleaning up previous build files" + rm -rf build + + docker run --rm -v $(pwd):/workspace openapitools/openapi-generator-cli:v5.2.0 generate \ + --input-spec "/workspace/$oas_file" \ + --generator-name python \ + --config /workspace/codegen/openapi-config.json \ + --output /workspace/build \ + --template-dir "/workspace/$template_dir" +} + +verify_spec_version $version + +data_oas="codegen/apis/static/$version/data_$version.oas.yaml" +control_oas="codegen/apis/static/$version/control_$version.oas.yaml" +verify_spec_file_exists $data_oas +verify_spec_file_exists $control_oas + +# Remove old generated files +rm -rf pinecone/core/client +mkdir -p pinecone/core/client + +generate_client $data_oas +cp -r build/pinecone/core/client pinecone/core + +# The openapi generator isn't really built to handle multiple spec files, +# so we have to manually merge the generated files +generate_client $control_oas + +# Concat data and control models/__init__.py files +cat pinecone/core/client/models/__init__.py >> build/pinecone/core/client/models/__init__.py +# Copy control models files and combined __init__ file into pinecone +cp -r build/pinecone/core/client/models/* pinecone/core/client/models +# Concat data and control apis/__init__.py files +cat pinecone/core/client/apis/__init__.py >> build/pinecone/core/client/apis/__init__.py +# Copy control apis files and combined __init__ file into pinecone +cp -r build/pinecone/core/client/apis/* pinecone/core/client/apis + +# Format generated files +poetry run black pinecone/core diff --git a/codegen/openapi-config.json b/codegen/openapi-config.json new file mode 100644 index 000000000..70b1781b0 --- /dev/null +++ b/codegen/openapi-config.json @@ -0,0 +1,4 @@ +{ + "packageName": "pinecone.core.client", + "pythonAttrNoneIfUnset": true +} \ No newline at end of file diff --git a/codegen/python-oas-templates b/codegen/python-oas-templates new file mode 160000 index 000000000..b72bd5bf2 --- /dev/null +++ b/codegen/python-oas-templates @@ -0,0 +1 @@ +Subproject commit b72bd5bf2b03a995f3e78c16bf0483dc756f6506 From e248ddaa9e8be5b671026d7813becb5c9973c144 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 24 Jun 2024 15:21:00 -0400 Subject: [PATCH 02/13] Update codegen script to refresh apis submodule --- codegen/build-oas.sh | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index e9c0028a9..5760e9912 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -5,12 +5,18 @@ version='2024-04' rm -rf build mkdir build -# pushd codegen/apis -# just build -# popd +update_apis_repo() { + echo "Updating apis repo" + pushd codegen/apis + git fetch + git pull + just build + popd +} verify_spec_version() { local version=$1 + echo "Verifying spec version $version exists in apis repo" if [ -z "$version" ]; then echo "Version is required" exit 1 @@ -55,31 +61,35 @@ generate_client() { --template-dir "/workspace/$template_dir" } +update_apis_repo verify_spec_version $version -data_oas="codegen/apis/static/$version/data_$version.oas.yaml" -control_oas="codegen/apis/static/$version/control_$version.oas.yaml" -verify_spec_file_exists $data_oas -verify_spec_file_exists $control_oas - # Remove old generated files rm -rf pinecone/core/client mkdir -p pinecone/core/client +# Generate data plane client +data_oas="codegen/apis/static/$version/data_$version.oas.yaml" +verify_spec_file_exists $data_oas generate_client $data_oas cp -r build/pinecone/core/client pinecone/core -# The openapi generator isn't really built to handle multiple spec files, -# so we have to manually merge the generated files +# Generate control plane client +control_oas="codegen/apis/static/$version/control_$version.oas.yaml" +verify_spec_file_exists $control_oas generate_client $control_oas -# Concat data and control models/__init__.py files +# The openapi generator isn't really built to handle multiple spec files, +# so we have to manually merge the generated outputs from data plane and +# control plane. + +# 1. Concat data and control models/__init__.py files cat pinecone/core/client/models/__init__.py >> build/pinecone/core/client/models/__init__.py -# Copy control models files and combined __init__ file into pinecone +# 2. Copy control models files and combined __init__ file into pinecone cp -r build/pinecone/core/client/models/* pinecone/core/client/models -# Concat data and control apis/__init__.py files +# 3. Concat data and control apis/__init__.py files cat pinecone/core/client/apis/__init__.py >> build/pinecone/core/client/apis/__init__.py -# Copy control apis files and combined __init__ file into pinecone +# 4. Copy control apis files and combined __init__ file into pinecone cp -r build/pinecone/core/client/apis/* pinecone/core/client/apis # Format generated files From b55b0729b7eec001a973acf34d92e7eb3a6b9494 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 25 Jun 2024 11:20:59 -0400 Subject: [PATCH 03/13] Experiment with generating two packages --- codegen/apis | 2 +- codegen/build-oas.sh | 41 ++++++++++++++--------------- codegen/openapi-config.control.json | 4 +++ codegen/openapi-config.data.json | 4 +++ codegen/openapi-config.json | 4 --- 5 files changed, 29 insertions(+), 26 deletions(-) create mode 100644 codegen/openapi-config.control.json create mode 100644 codegen/openapi-config.data.json delete mode 100644 codegen/openapi-config.json diff --git a/codegen/apis b/codegen/apis index 94edff09f..4de44568f 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 94edff09fa52e8a0c800602798b3fba36f7465b8 +Subproject commit 4de44568f98556d29e8044c8146b572d2396cb05 diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 5760e9912..9173164b2 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -38,6 +38,7 @@ verify_spec_file_exists() { generate_client() { local oas_file=$1 + local openapi_generator_config=$2 local template_dir="codegen/python-oas-templates/templates5.2.0" if [ ! -f "$oas_file" ]; then @@ -56,7 +57,7 @@ generate_client() { docker run --rm -v $(pwd):/workspace openapitools/openapi-generator-cli:v5.2.0 generate \ --input-spec "/workspace/$oas_file" \ --generator-name python \ - --config /workspace/codegen/openapi-config.json \ + --config "/workspace/$openapi_generator_config" \ --output /workspace/build \ --template-dir "/workspace/$template_dir" } @@ -64,33 +65,31 @@ generate_client() { update_apis_repo verify_spec_version $version -# Remove old generated files -rm -rf pinecone/core/client -mkdir -p pinecone/core/client - # Generate data plane client data_oas="codegen/apis/static/$version/data_$version.oas.yaml" +data_config="codegen/openapi-config.data.json" verify_spec_file_exists $data_oas -generate_client $data_oas -cp -r build/pinecone/core/client pinecone/core +generate_client $data_oas $data_config +rm -rf pinecone/core/data +cp -r build/pinecone/core/data pinecone/core/data # Generate control plane client control_oas="codegen/apis/static/$version/control_$version.oas.yaml" +control_config="codegen/openapi-config.control.json" verify_spec_file_exists $control_oas -generate_client $control_oas - -# The openapi generator isn't really built to handle multiple spec files, -# so we have to manually merge the generated outputs from data plane and -# control plane. - -# 1. Concat data and control models/__init__.py files -cat pinecone/core/client/models/__init__.py >> build/pinecone/core/client/models/__init__.py -# 2. Copy control models files and combined __init__ file into pinecone -cp -r build/pinecone/core/client/models/* pinecone/core/client/models -# 3. Concat data and control apis/__init__.py files -cat pinecone/core/client/apis/__init__.py >> build/pinecone/core/client/apis/__init__.py -# 4. Copy control apis files and combined __init__ file into pinecone -cp -r build/pinecone/core/client/apis/* pinecone/core/client/apis +generate_client $control_oas $control_config +rm -rf pinecone/core/control +cp -r build/pinecone/core/control pinecone/core/control + + +# # 1. Concat data and control models/__init__.py files +# cat pinecone/core/client/models/__init__.py >> build/pinecone/core/client/models/__init__.py +# # 2. Copy control models files and combined __init__ file into pinecone +# cp -r build/pinecone/core/client/models/* pinecone/core/client/models +# # 3. Concat data and control apis/__init__.py files +# cat pinecone/core/client/apis/__init__.py >> build/pinecone/core/client/apis/__init__.py +# # 4. Copy control apis files and combined __init__ file into pinecone +# cp -r build/pinecone/core/client/apis/* pinecone/core/client/apis # Format generated files poetry run black pinecone/core diff --git a/codegen/openapi-config.control.json b/codegen/openapi-config.control.json new file mode 100644 index 000000000..c07f29519 --- /dev/null +++ b/codegen/openapi-config.control.json @@ -0,0 +1,4 @@ +{ + "packageName": "pinecone.core.control.client", + "pythonAttrNoneIfUnset": true +} \ No newline at end of file diff --git a/codegen/openapi-config.data.json b/codegen/openapi-config.data.json new file mode 100644 index 000000000..daf1314ec --- /dev/null +++ b/codegen/openapi-config.data.json @@ -0,0 +1,4 @@ +{ + "packageName": "pinecone.core.data.client", + "pythonAttrNoneIfUnset": true +} \ No newline at end of file diff --git a/codegen/openapi-config.json b/codegen/openapi-config.json deleted file mode 100644 index 70b1781b0..000000000 --- a/codegen/openapi-config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "packageName": "pinecone.core.client", - "pythonAttrNoneIfUnset": true -} \ No newline at end of file From 15aa28a300a2f5163d966f881ef96edc4104102b Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Tue, 25 Jun 2024 11:22:19 -0400 Subject: [PATCH 04/13] Experiment with generating two packages pinecone.core.data and pinecone.core.control --- pinecone/core/client/__init__.py | 28 - pinecone/core/client/models/__init__.py | 49 - pinecone/core/control/__init__.py | 0 pinecone/core/control/client/__init__.py | 28 + pinecone/core/control/client/api/__init__.py | 3 + .../client/api/manage_indexes_api.py | 38 +- pinecone/core/control/client/api_client.py | 847 ++++++++ pinecone/core/control/client/apis/__init__.py | 16 + .../{ => control}/client/configuration.py | 12 +- .../core/{ => control}/client/exceptions.py | 7 +- .../{ => control}/client/model/__init__.py | 0 .../client/model/collection_list.py | 8 +- .../client/model/collection_model.py | 10 +- .../client/model/configure_index_request.py | 8 +- .../model/configure_index_request_spec.py | 8 +- .../model/configure_index_request_spec_pod.py | 26 +- .../client/model/create_collection_request.py | 6 +- .../client/model/create_index_request.py | 59 +- .../client/model/error_response.py | 8 +- .../client/model/error_response_error.py | 6 +- .../control/client/model/index_dimension.py | 301 +++ .../{ => control}/client/model/index_list.py | 8 +- .../core/control/client/model/index_metric.py | 294 +++ .../{ => control}/client/model/index_model.py | 61 +- .../client/model/index_model_spec.py | 10 +- .../client/model/index_model_status.py | 6 +- .../core/control/client/model/index_name.py | 301 +++ .../{ => control}/client/model/pod_spec.py | 38 +- .../client/model/pod_spec_metadata_config.py | 6 +- .../control/client/model/pod_spec_replicas.py | 292 +++ .../control/client/model/pod_spec_shards.py | 292 +++ .../client/model/serverless_spec.py | 10 +- .../core/{ => control}/client/model_utils.py | 5 +- .../core/control/client/models/__init__.py | 32 + pinecone/core/{ => control}/client/rest.py | 6 +- pinecone/core/data/__init__.py | 0 pinecone/core/data/client/__init__.py | 28 + .../core/{ => data}/client/api/__init__.py | 2 +- .../{ => data}/client/api/data_plane_api.py | 50 +- pinecone/core/{ => data}/client/api_client.py | 14 +- .../core/{ => data}/client/apis/__init__.py | 3 +- pinecone/core/data/client/configuration.py | 487 +++++ pinecone/core/data/client/exceptions.py | 156 ++ pinecone/core/data/client/model/__init__.py | 5 + .../{ => data}/client/model/delete_request.py | 12 +- .../model/describe_index_stats_request.py | 12 +- .../model/describe_index_stats_response.py | 18 +- .../{ => data}/client/model/fetch_response.py | 12 +- .../core/{ => data}/client/model/list_item.py | 8 +- .../{ => data}/client/model/list_response.py | 14 +- .../client/model/namespace_summary.py | 8 +- .../{ => data}/client/model/pagination.py | 8 +- .../{ => data}/client/model/protobuf_any.py | 8 +- .../client/model/protobuf_null_value.py | 16 +- .../{ => data}/client/model/query_request.py | 16 +- .../{ => data}/client/model/query_response.py | 14 +- .../{ => data}/client/model/query_vector.py | 10 +- .../{ => data}/client/model/rpc_status.py | 10 +- .../{ => data}/client/model/scored_vector.py | 10 +- .../client/model/single_query_results.py | 10 +- .../{ => data}/client/model/sparse_values.py | 16 +- .../{ => data}/client/model/update_request.py | 18 +- .../{ => data}/client/model/upsert_request.py | 14 +- .../client/model/upsert_response.py | 8 +- .../core/{ => data}/client/model/usage.py | 8 +- .../core/{ => data}/client/model/vector.py | 10 +- pinecone/core/data/client/model_utils.py | 1886 +++++++++++++++++ pinecone/core/data/client/models/__init__.py | 33 + pinecone/core/data/client/rest.py | 404 ++++ 69 files changed, 5739 insertions(+), 418 deletions(-) delete mode 100644 pinecone/core/client/__init__.py delete mode 100644 pinecone/core/client/models/__init__.py create mode 100644 pinecone/core/control/__init__.py create mode 100644 pinecone/core/control/client/__init__.py create mode 100644 pinecone/core/control/client/api/__init__.py rename pinecone/core/{ => control}/client/api/manage_indexes_api.py (96%) create mode 100644 pinecone/core/control/client/api_client.py create mode 100644 pinecone/core/control/client/apis/__init__.py rename pinecone/core/{ => control}/client/configuration.py (98%) rename pinecone/core/{ => control}/client/exceptions.py (98%) rename pinecone/core/{ => control}/client/model/__init__.py (100%) rename pinecone/core/{ => control}/client/model/collection_list.py (97%) rename pinecone/core/{ => control}/client/model/collection_model.py (97%) rename pinecone/core/{ => control}/client/model/configure_index_request.py (97%) rename pinecone/core/{ => control}/client/model/configure_index_request_spec.py (97%) rename pinecone/core/{ => control}/client/model/configure_index_request_spec_pod.py (93%) rename pinecone/core/{ => control}/client/model/create_collection_request.py (98%) rename pinecone/core/{ => control}/client/model/create_index_request.py (85%) rename pinecone/core/{ => control}/client/model/error_response.py (97%) rename pinecone/core/{ => control}/client/model/error_response_error.py (98%) create mode 100644 pinecone/core/control/client/model/index_dimension.py rename pinecone/core/{ => control}/client/model/index_list.py (97%) create mode 100644 pinecone/core/control/client/model/index_metric.py rename pinecone/core/{ => control}/client/model/index_model.py (84%) rename pinecone/core/{ => control}/client/model/index_model_spec.py (97%) rename pinecone/core/{ => control}/client/model/index_model_status.py (98%) create mode 100644 pinecone/core/control/client/model/index_name.py rename pinecone/core/{ => control}/client/model/pod_spec.py (89%) rename pinecone/core/{ => control}/client/model/pod_spec_metadata_config.py (98%) create mode 100644 pinecone/core/control/client/model/pod_spec_replicas.py create mode 100644 pinecone/core/control/client/model/pod_spec_shards.py rename pinecone/core/{ => control}/client/model/serverless_spec.py (97%) rename pinecone/core/{ => control}/client/model_utils.py (99%) create mode 100644 pinecone/core/control/client/models/__init__.py rename pinecone/core/{ => control}/client/rest.py (99%) create mode 100644 pinecone/core/data/__init__.py create mode 100644 pinecone/core/data/client/__init__.py rename pinecone/core/{ => data}/client/api/__init__.py (74%) rename pinecone/core/{ => data}/client/api/data_plane_api.py (94%) rename pinecone/core/{ => data}/client/api_client.py (98%) rename pinecone/core/{ => data}/client/apis/__init__.py (75%) create mode 100644 pinecone/core/data/client/configuration.py create mode 100644 pinecone/core/data/client/exceptions.py create mode 100644 pinecone/core/data/client/model/__init__.py rename pinecone/core/{ => data}/client/model/delete_request.py (93%) rename pinecone/core/{ => data}/client/model/describe_index_stats_request.py (94%) rename pinecone/core/{ => data}/client/model/describe_index_stats_response.py (90%) rename pinecone/core/{ => data}/client/model/fetch_response.py (97%) rename pinecone/core/{ => data}/client/model/list_item.py (98%) rename pinecone/core/{ => data}/client/model/list_response.py (96%) rename pinecone/core/{ => data}/client/model/namespace_summary.py (98%) rename pinecone/core/{ => data}/client/model/pagination.py (98%) rename pinecone/core/{ => data}/client/model/protobuf_any.py (98%) rename pinecone/core/{ => data}/client/model/protobuf_null_value.py (91%) rename pinecone/core/{ => data}/client/model/query_request.py (95%) rename pinecone/core/{ => data}/client/model/query_response.py (96%) rename pinecone/core/{ => data}/client/model/query_vector.py (97%) rename pinecone/core/{ => data}/client/model/rpc_status.py (97%) rename pinecone/core/{ => data}/client/model/scored_vector.py (97%) rename pinecone/core/{ => data}/client/model/single_query_results.py (97%) rename pinecone/core/{ => data}/client/model/sparse_values.py (95%) rename pinecone/core/{ => data}/client/model/update_request.py (94%) rename pinecone/core/{ => data}/client/model/upsert_request.py (96%) rename pinecone/core/{ => data}/client/model/upsert_response.py (98%) rename pinecone/core/{ => data}/client/model/usage.py (98%) rename pinecone/core/{ => data}/client/model/vector.py (97%) create mode 100644 pinecone/core/data/client/model_utils.py create mode 100644 pinecone/core/data/client/models/__init__.py create mode 100644 pinecone/core/data/client/rest.py diff --git a/pinecone/core/client/__init__.py b/pinecone/core/client/__init__.py deleted file mode 100644 index b8bbd9ff1..000000000 --- a/pinecone/core/client/__init__.py +++ /dev/null @@ -1,28 +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 - - The version of the OpenAPI document: v1 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.core.client.api_client import ApiClient - -# import Configuration -from pinecone.core.client.configuration import Configuration - -# import exceptions -from pinecone.core.client.exceptions import PineconeException -from pinecone.core.client.exceptions import PineconeApiAttributeError -from pinecone.core.client.exceptions import PineconeApiTypeError -from pinecone.core.client.exceptions import PineconeApiValueError -from pinecone.core.client.exceptions import PineconeApiKeyError -from pinecone.core.client.exceptions import PineconeApiException diff --git a/pinecone/core/client/models/__init__.py b/pinecone/core/client/models/__init__.py deleted file mode 100644 index 8e4aa36c5..000000000 --- a/pinecone/core/client/models/__init__.py +++ /dev/null @@ -1,49 +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.client.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.client.model.collection_list import CollectionList -from pinecone.core.client.model.collection_model import CollectionModel -from pinecone.core.client.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.client.model.configure_index_request_spec import ConfigureIndexRequestSpec -from pinecone.core.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod -from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_index_request import CreateIndexRequest -from pinecone.core.client.model.delete_request import DeleteRequest -from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.model.error_response import ErrorResponse -from pinecone.core.client.model.error_response_error import ErrorResponseError -from pinecone.core.client.model.fetch_response import FetchResponse -from pinecone.core.client.model.index_list import IndexList -from pinecone.core.client.model.index_model import IndexModel -from pinecone.core.client.model.index_model_spec import IndexModelSpec -from pinecone.core.client.model.index_model_status import IndexModelStatus -from pinecone.core.client.model.list_item import ListItem -from pinecone.core.client.model.list_response import ListResponse -from pinecone.core.client.model.namespace_summary import NamespaceSummary -from pinecone.core.client.model.pagination import Pagination -from pinecone.core.client.model.pod_spec import PodSpec -from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig -from pinecone.core.client.model.protobuf_any import ProtobufAny -from pinecone.core.client.model.protobuf_null_value import ProtobufNullValue -from pinecone.core.client.model.query_request import QueryRequest -from pinecone.core.client.model.query_response import QueryResponse -from pinecone.core.client.model.query_vector import QueryVector -from pinecone.core.client.model.rpc_status import RpcStatus -from pinecone.core.client.model.scored_vector import ScoredVector -from pinecone.core.client.model.serverless_spec import ServerlessSpec -from pinecone.core.client.model.single_query_results import SingleQueryResults -from pinecone.core.client.model.sparse_values import SparseValues -from pinecone.core.client.model.update_request import UpdateRequest -from pinecone.core.client.model.upsert_request import UpsertRequest -from pinecone.core.client.model.upsert_response import UpsertResponse -from pinecone.core.client.model.usage import Usage -from pinecone.core.client.model.vector import Vector diff --git a/pinecone/core/control/__init__.py b/pinecone/core/control/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/pinecone/core/control/client/__init__.py b/pinecone/core/control/client/__init__.py new file mode 100644 index 000000000..88a122a68 --- /dev/null +++ b/pinecone/core/control/client/__init__.py @@ -0,0 +1,28 @@ +# 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 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from pinecone.core.control.client.api_client import ApiClient + +# import Configuration +from pinecone.core.control.client.configuration import Configuration + +# import exceptions +from pinecone.core.control.client.exceptions import PineconeException +from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiTypeError +from pinecone.core.control.client.exceptions import PineconeApiValueError +from pinecone.core.control.client.exceptions import PineconeApiKeyError +from pinecone.core.control.client.exceptions import PineconeApiException diff --git a/pinecone/core/control/client/api/__init__.py b/pinecone/core/control/client/api/__init__.py new file mode 100644 index 000000000..151eddb0d --- /dev/null +++ b/pinecone/core/control/client/api/__init__.py @@ -0,0 +1,3 @@ +# do not import all apis into this module because that uses a lot of memory and stack frames +# if you need the ability to import all apis from one package, import them with +# from pinecone.core.control.client.apis import ManageIndexesApi diff --git a/pinecone/core/client/api/manage_indexes_api.py b/pinecone/core/control/client/api/manage_indexes_api.py similarity index 96% rename from pinecone/core/client/api/manage_indexes_api.py rename to pinecone/core/control/client/api/manage_indexes_api.py index 64f35d46e..bf553b01f 100644 --- a/pinecone/core/client/api/manage_indexes_api.py +++ b/pinecone/core/control/client/api/manage_indexes_api.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.control.client.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, @@ -21,14 +21,14 @@ none_type, validate_and_convert_types, ) -from pinecone.core.client.model.collection_list import CollectionList -from pinecone.core.client.model.collection_model import CollectionModel -from pinecone.core.client.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.client.model.create_index_request import CreateIndexRequest -from pinecone.core.client.model.error_response import ErrorResponse -from pinecone.core.client.model.index_list import IndexList -from pinecone.core.client.model.index_model import IndexModel +from pinecone.core.control.client.model.collection_list import CollectionList +from pinecone.core.control.client.model.collection_model import CollectionModel +from pinecone.core.control.client.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest +from pinecone.core.control.client.model.create_index_request import CreateIndexRequest +from pinecone.core.control.client.model.error_response import ErrorResponse +from pinecone.core.control.client.model.index_list import IndexList +from pinecone.core.control.client.model.index_model import IndexModel class ManageIndexesApi(object): @@ -145,7 +145,7 @@ def __configure_index(self, index_name, configure_index_request, **kwargs): def __create_collection(self, create_collection_request, **kwargs): """Create a collection # noqa: E501 - This operation creates a Pinecone collection. Serverless and starter indexes do not support collections. # 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 @@ -236,7 +236,7 @@ def __create_collection(self, create_collection_request, **kwargs): 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/docs/manage-indexes#create-a-serverless-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 @@ -327,7 +327,7 @@ def __create_index(self, create_index_request, **kwargs): def __delete_collection(self, collection_name, **kwargs): """Delete a collection # noqa: E501 - This operation deletes an existing collection. Serverless and starter indexes do not support collections. # 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 @@ -359,7 +359,7 @@ def __delete_collection(self, collection_name, **kwargs): async_req (bool): execute request asynchronously Returns: - str + None If the method is called asynchronously, returns the request thread. """ @@ -375,7 +375,7 @@ def __delete_collection(self, collection_name, **kwargs): self.delete_collection = _Endpoint( settings={ - "response_type": (str,), + "response_type": None, "auth": ["ApiKeyAuth"], "endpoint_path": "/collections/{collection_name}", "operation_id": "delete_collection", @@ -413,7 +413,7 @@ def __delete_collection(self, collection_name, **kwargs): "collection_format_map": {}, }, headers_map={ - "accept": ["text/plain", "application/json"], + "accept": ["application/json"], "content_type": [], }, api_client=api_client, @@ -519,7 +519,7 @@ def __delete_index(self, index_name, **kwargs): def __describe_collection(self, collection_name, **kwargs): """Describe a collection # noqa: E501 - This operation gets a description of a collection. Serverless and starter indexes do not support collections. # 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 @@ -711,7 +711,7 @@ def __describe_index(self, index_name, **kwargs): def __list_collections(self, **kwargs): """List collections # noqa: E501 - This operation returns a list of all collections in a project. Serverless and starter indexes do not support 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 diff --git a/pinecone/core/control/client/api_client.py b/pinecone/core/control/client/api_client.py new file mode 100644 index 000000000..c36b00c7e --- /dev/null +++ b/pinecone/core/control/client/api_client.py @@ -0,0 +1,847 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import json +import atexit +import mimetypes +from multiprocessing.pool import ThreadPool +import io +import os +import re +import typing +from urllib.parse import quote +from urllib3.fields import RequestField + + +from pinecone.core.control.client import rest +from pinecone.core.control.client.configuration import Configuration +from pinecone.core.control.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException +from pinecone.core.control.client.model_utils import ( + ModelNormal, + ModelSimple, + ModelComposed, + check_allowed_values, + check_validations, + date, + datetime, + deserialize_file, + file_type, + model_to_dict, + none_type, + validate_and_convert_types, +) + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1): + if configuration is None: + configuration = Configuration.get_default_copy() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + 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._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 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: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None, + ): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params["Cookie"] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, collection_formats) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, collection_formats) + post_params.extend(self.files_parameters(files)) + if header_params["Content-Type"].startswith("multipart"): + post_params = self.parameters_to_multipart(post_params, (dict)) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings, resource_path, method, body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + try: + # perform request and return response + response_data = self.request( + method, + url, + query_params=query_params, + headers=header_params, + post_params=post_params, + body=body, + _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 + return return_data + + # deserialize response data + if response_type: + if response_type != (file_type,): + encoding = "utf-8" + content_type = response_data.getheader("content-type") + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + if match: + encoding = match.group(1) + response_data.data = response_data.data.decode(encoding) + + return_data = self.deserialize(response_data, response_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 parameters_to_multipart(self, params, collection_types): + """Get parameters as list of tuples, formatting as json if value is collection_types + + :param params: Parameters as list of two-tuples + :param dict collection_types: Parameter collection types + :return: Parameters as list of tuple or urllib3.fields.RequestField + """ + new_params = [] + if collection_types is None: + collection_types = dict + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json + v = json.dumps(v, ensure_ascii=False).encode("utf-8") + field = RequestField(k, v) + field.make_multipart(content_type="application/json; charset=utf-8") + new_params.append(field) + else: + new_params.append((k, v)) + return new_params + + @classmethod + def sanitize_for_serialization(cls, obj): + """Prepares data for transmission before it is sent with the rest client + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + 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, none_type, bool)): + 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__)) + + def deserialize(self, response, response_type, _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, self.configuration, 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=self.configuration + ) + return deserialized_data + + def call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + async_req: typing.Optional[bool] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None, + ): + """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 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`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """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 = [] + 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 + + @staticmethod + def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: + file_data = file_instance.read() + file_instance.close() + return file_data + + def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.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) + filedata = self.get_file_data_and_close_file(file_instance) + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" + params.append(tuple([param_name, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """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) + + def select_header_content_type(self, content_types): + """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] + + def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of _encoder.default(). + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting["in"] == "cookie": + headers["Cookie"] = auth_setting["value"] + elif auth_setting["in"] == "header": + if auth_setting["type"] != "http-signature": + headers[auth_setting["key"]] = auth_setting["value"] + elif auth_setting["in"] == "query": + querys.append((auth_setting["key"], auth_setting["value"])) + else: + raise PineconeApiValueError("Authentication token must be in `query` or `header`") + + +class Endpoint(object): + def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None): + """Creates an endpoint + + Args: + settings (dict): see below key value pairs + 'response_type' (tuple/None): response type + 'auth' (list): a list of auth type keys + 'endpoint_path' (str): the endpoint path + 'operation_id' (str): endpoint string identifier + 'http_method' (str): POST/PUT/PATCH/GET etc + 'servers' (list): list of str servers that this endpoint is at + params_map (dict): see below key value pairs + 'all' (list): list of str endpoint parameter names + 'required' (list): list of required parameter names + 'nullable' (list): list of nullable parameter names + 'enum' (list): list of parameters with enum values + 'validation' (list): list of parameters with validations + root_map + 'validations' (dict): the dict mapping endpoint parameter tuple + paths to their validation dictionaries + 'allowed_values' (dict): the dict mapping endpoint parameter + tuple paths to their allowed_values (enum) dictionaries + 'openapi_types' (dict): param_name to openapi type + 'attribute_map' (dict): param_name to camelCase name + 'location_map' (dict): param_name to 'body', 'file', 'form', + 'header', 'path', 'query' + collection_format_map (dict): param_name to `csv` etc. + headers_map (dict): see below key value pairs + 'accept' (list): list of Accept header strings + 'content_type' (list): list of Content-Type header strings + api_client (ApiClient) api client instance + callable (function): the function which is invoked when the + Endpoint is called + """ + self.settings = settings + self.params_map = params_map + self.params_map["all"].extend( + [ + "async_req", + "_host_index", + "_preload_content", + "_request_timeout", + "_return_http_data_only", + "_check_input_type", + "_check_return_type", + ] + ) + self.params_map["nullable"].extend(["_request_timeout"]) + self.validations = root_map["validations"] + self.allowed_values = root_map["allowed_values"] + self.openapi_types = root_map["openapi_types"] + extra_types = { + "async_req": (bool,), + "_host_index": (none_type, int), + "_preload_content": (bool,), + "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]), + "_return_http_data_only": (bool,), + "_check_input_type": (bool,), + "_check_return_type": (bool,), + } + self.openapi_types.update(extra_types) + self.attribute_map = root_map["attribute_map"] + self.location_map = root_map["location_map"] + self.collection_format_map = root_map["collection_format_map"] + self.headers_map = headers_map + self.api_client = api_client + self.callable = callable + + def __validate_inputs(self, kwargs): + for param in self.params_map["enum"]: + if param in kwargs: + check_allowed_values(self.allowed_values, (param,), kwargs[param]) + + for param in self.params_map["validation"]: + if param in kwargs: + check_validations( + self.validations, (param,), kwargs[param], configuration=self.api_client.configuration + ) + + if kwargs["_check_input_type"] is False: + return + + for key, value in kwargs.items(): + fixed_val = validate_and_convert_types( + value, + self.openapi_types[key], + [key], + False, + kwargs["_check_input_type"], + configuration=self.api_client.configuration, + ) + kwargs[key] = fixed_val + + def __gather_params(self, kwargs): + params = {"body": None, "collection_format": {}, "file": {}, "form": [], "header": {}, "path": {}, "query": []} + + for param_name, param_value in kwargs.items(): + param_location = self.location_map.get(param_name) + if param_location is None: + continue + if param_location: + if param_location == "body": + params["body"] = param_value + continue + base_name = self.attribute_map[param_name] + if param_location == "form" and self.openapi_types[param_name] == (file_type,): + params["file"][param_name] = [param_value] + elif param_location == "form" and self.openapi_types[param_name] == ([file_type],): + # param_value is already a list + params["file"][param_name] = param_value + elif param_location in {"form", "query"}: + param_value_full = (base_name, param_value) + params[param_location].append(param_value_full) + if param_location not in {"form", "query"}: + params[param_location][base_name] = param_value + collection_format = self.collection_format_map.get(param_name) + if collection_format: + params["collection_format"][base_name] = collection_format + + return params + + def __call__(self, *args, **kwargs): + """This method is invoked when endpoints are called + Example: + + api_instance = ManageIndexesApi() + api_instance.configure_index # this is an instance of the class Endpoint + api_instance.configure_index() # this invokes api_instance.configure_index.__call__() + which then invokes the callable functions stored in that endpoint at + api_instance.configure_index.callable or self.callable in this class + + """ + return self.callable(self, *args, **kwargs) + + def call_with_http_info(self, **kwargs): + + try: + index = ( + self.api_client.configuration.server_operation_index.get( + self.settings["operation_id"], self.api_client.configuration.server_index + ) + if kwargs["_host_index"] is None + else kwargs["_host_index"] + ) + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings["operation_id"], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings["servers"] + ) + except IndexError: + if self.settings["servers"]: + raise PineconeApiValueError( + "Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"]) + ) + _host = None + + for key, value in kwargs.items(): + if key not in self.params_map["all"]: + raise PineconeApiTypeError( + "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.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 self.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, self.settings["operation_id"]) + ) + + for key in self.params_map["required"]: + if key not in kwargs.keys(): + raise PineconeApiValueError( + "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"]) + ) + + self.__validate_inputs(kwargs) + + params = self.__gather_params(kwargs) + + accept_headers_list = self.headers_map["accept"] + if accept_headers_list: + params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list) + + content_type_headers_list = self.headers_map["content_type"] + if content_type_headers_list: + header_list = self.api_client.select_header_content_type(content_type_headers_list) + params["header"]["Content-Type"] = header_list + + return self.api_client.call_api( + self.settings["endpoint_path"], + self.settings["http_method"], + params["path"], + params["query"], + params["header"], + body=params["body"], + post_params=params["form"], + files=params["file"], + response_type=self.settings["response_type"], + auth_settings=self.settings["auth"], + async_req=kwargs["async_req"], + _check_type=kwargs["_check_return_type"], + _return_http_data_only=kwargs["_return_http_data_only"], + _preload_content=kwargs["_preload_content"], + _request_timeout=kwargs["_request_timeout"], + _host=_host, + collection_formats=params["collection_format"], + ) diff --git a/pinecone/core/control/client/apis/__init__.py b/pinecone/core/control/client/apis/__init__.py new file mode 100644 index 000000000..55a7599b7 --- /dev/null +++ b/pinecone/core/control/client/apis/__init__.py @@ -0,0 +1,16 @@ +# 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.control.client.api.manage_indexes_api import ManageIndexesApi diff --git a/pinecone/core/client/configuration.py b/pinecone/core/control/client/configuration.py similarity index 98% rename from pinecone/core/client/configuration.py rename to pinecone/core/control/client/configuration.py index 9ecbec753..c25bb2319 100644 --- a/pinecone/core/client/configuration.py +++ b/pinecone/core/control/client/configuration.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -15,7 +15,7 @@ import urllib3 from http import client as http_client -from pinecone.core.client.exceptions import PineconeApiValueError +from pinecone.core.control.client.exceptions import PineconeApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { @@ -97,7 +97,7 @@ class Configuration(object): You can programmatically set the cookie: - conf = pinecone.core.client.Configuration( + conf = pinecone.core.control.client.Configuration( api_key={'cookieAuth': 'abc123'} api_key_prefix={'cookieAuth': 'JSESSIONID'} ) @@ -165,7 +165,7 @@ def __init__( self.logger = {} """Logging Settings """ - self.logger["package_logger"] = logging.getLogger("pinecone.core.client") + self.logger["package_logger"] = logging.getLogger("pinecone.core.control.client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") self.logger_format = "%(asctime)s %(levelname)s %(message)s" """Log format @@ -416,7 +416,7 @@ def to_debug_report(self): "Python SDK Debug Report:\n" "OS: {env}\n" "Python Version: {pyversion}\n" - "Version of the API: v1\n" + "Version of the API: 2024-04\n" "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) ) @@ -428,7 +428,7 @@ def get_host_settings(self): return [ { "url": "https://api.pinecone.io", - "description": "Production API endpoints; unversioned legacy.", + "description": "Production API endpoints", } ] diff --git a/pinecone/core/client/exceptions.py b/pinecone/core/control/client/exceptions.py similarity index 98% rename from pinecone/core/client/exceptions.py rename to pinecone/core/control/client/exceptions.py index 0cabf8083..aac96ceaa 100644 --- a/pinecone/core/client/exceptions.py +++ b/pinecone/core/control/client/exceptions.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -96,6 +96,7 @@ def __init__(self, msg, path_to_item=None): class PineconeApiException(PineconeException): + def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status @@ -121,21 +122,25 @@ def __str__(self): class NotFoundException(PineconeApiException): + def __init__(self, status=None, reason=None, http_resp=None): super(NotFoundException, self).__init__(status, reason, http_resp) class UnauthorizedException(PineconeApiException): + def __init__(self, status=None, reason=None, http_resp=None): super(UnauthorizedException, self).__init__(status, reason, http_resp) class ForbiddenException(PineconeApiException): + def __init__(self, status=None, reason=None, http_resp=None): super(ForbiddenException, self).__init__(status, reason, http_resp) class ServiceException(PineconeApiException): + def __init__(self, status=None, reason=None, http_resp=None): super(ServiceException, self).__init__(status, reason, http_resp) diff --git a/pinecone/core/client/model/__init__.py b/pinecone/core/control/client/model/__init__.py similarity index 100% rename from pinecone/core/client/model/__init__.py rename to pinecone/core/control/client/model/__init__.py diff --git a/pinecone/core/client/model/collection_list.py b/pinecone/core/control/client/model/collection_list.py similarity index 97% rename from pinecone/core/client/model/collection_list.py rename to pinecone/core/control/client/model/collection_list.py index 580789991..b691b88e5 100644 --- a/pinecone/core/client/model/collection_list.py +++ b/pinecone/core/control/client/model/collection_list.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.collection_model import CollectionModel + from pinecone.core.control.client.model.collection_model import CollectionModel globals()["CollectionModel"] = CollectionModel diff --git a/pinecone/core/client/model/collection_model.py b/pinecone/core/control/client/model/collection_model.py similarity index 97% rename from pinecone/core/client/model/collection_model.py rename to pinecone/core/control/client/model/collection_model.py index b461d832b..968f8fdea 100644 --- a/pinecone/core/client/model/collection_model.py +++ b/pinecone/core/control/client/model/collection_model.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class CollectionModel(ModelNormal): @@ -130,7 +130,7 @@ def _from_openapi_data(cls, name, status, environment, *args, **kwargs): # noqa """CollectionModel - a model defined in OpenAPI Args: - name (str): + name (str): The name of the collection. status (str): The status of the collection. environment (str): The environment where the collection is hosted. @@ -227,7 +227,7 @@ def __init__(self, name, status, environment, *args, **kwargs): # noqa: E501 """CollectionModel - a model defined in OpenAPI Args: - name (str): + name (str): The name of the collection. status (str): The status of the collection. environment (str): The environment where the collection is hosted. diff --git a/pinecone/core/client/model/configure_index_request.py b/pinecone/core/control/client/model/configure_index_request.py similarity index 97% rename from pinecone/core/client/model/configure_index_request.py rename to pinecone/core/control/client/model/configure_index_request.py index cf3eea58d..ee3ff0678 100644 --- a/pinecone/core/client/model/configure_index_request.py +++ b/pinecone/core/control/client/model/configure_index_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.configure_index_request_spec import ConfigureIndexRequestSpec + from pinecone.core.control.client.model.configure_index_request_spec import ConfigureIndexRequestSpec globals()["ConfigureIndexRequestSpec"] = ConfigureIndexRequestSpec diff --git a/pinecone/core/client/model/configure_index_request_spec.py b/pinecone/core/control/client/model/configure_index_request_spec.py similarity index 97% rename from pinecone/core/client/model/configure_index_request_spec.py rename to pinecone/core/control/client/model/configure_index_request_spec.py index e9285a60d..e5df7e80c 100644 --- a/pinecone/core/client/model/configure_index_request_spec.py +++ b/pinecone/core/control/client/model/configure_index_request_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod + from pinecone.core.control.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod globals()["ConfigureIndexRequestSpecPod"] = ConfigureIndexRequestSpecPod diff --git a/pinecone/core/client/model/configure_index_request_spec_pod.py b/pinecone/core/control/client/model/configure_index_request_spec_pod.py similarity index 93% rename from pinecone/core/client/model/configure_index_request_spec_pod.py rename to pinecone/core/control/client/model/configure_index_request_spec_pod.py index c0774a180..2f1d46239 100644 --- a/pinecone/core/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/control/client/model/configure_index_request_spec_pod.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,13 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas + + globals()["PodSpecReplicas"] = PodSpecReplicas class ConfigureIndexRequestSpecPod(ModelNormal): @@ -55,11 +61,7 @@ class ConfigureIndexRequestSpecPod(ModelNormal): allowed_values = {} - validations = { - ("replicas",): { - "inclusive_minimum": 1, - }, - } + validations = {} @cached_property def additional_properties_type(): @@ -67,6 +69,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ + lazy_import() return ( bool, date, @@ -91,8 +94,9 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { - "replicas": (int,), # noqa: E501 + "replicas": (PodSpecReplicas,), # noqa: E501 "pod_type": (str,), # noqa: E501 } @@ -145,7 +149,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - 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 + replicas (PodSpecReplicas): [optional] # 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 """ @@ -233,7 +237,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - 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 + replicas (PodSpecReplicas): [optional] # 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 """ diff --git a/pinecone/core/client/model/create_collection_request.py b/pinecone/core/control/client/model/create_collection_request.py similarity index 98% rename from pinecone/core/client/model/create_collection_request.py rename to pinecone/core/control/client/model/create_collection_request.py index 93dd4b050..c9e1af7e7 100644 --- a/pinecone/core/client/model/create_collection_request.py +++ b/pinecone/core/control/client/model/create_collection_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class CreateCollectionRequest(ModelNormal): diff --git a/pinecone/core/client/model/create_index_request.py b/pinecone/core/control/client/model/create_index_request.py similarity index 85% rename from pinecone/core/client/model/create_index_request.py rename to pinecone/core/control/client/model/create_index_request.py index 6ce5c4d2e..dcd5c8d94 100644 --- a/pinecone/core/client/model/create_index_request.py +++ b/pinecone/core/control/client/model/create_index_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,17 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.control.client.model.index_dimension import IndexDimension + from pinecone.core.control.client.model.index_metric import IndexMetric + from pinecone.core.control.client.model.index_name import IndexName + + globals()["IndexDimension"] = IndexDimension + globals()["IndexMetric"] = IndexMetric + globals()["IndexName"] = IndexName class CreateIndexRequest(ModelNormal): @@ -53,24 +63,9 @@ class CreateIndexRequest(ModelNormal): as additional properties values. """ - allowed_values = { - ("metric",): { - "COSINE": "cosine", - "EUCLIDEAN": "euclidean", - "DOTPRODUCT": "dotproduct", - }, - } + allowed_values = {} - validations = { - ("name",): { - "max_length": 45, - "min_length": 1, - }, - ("dimension",): { - "inclusive_maximum": 20000, - "inclusive_minimum": 1, - }, - } + validations = {} @cached_property def additional_properties_type(): @@ -78,6 +73,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ + lazy_import() return ( bool, date, @@ -102,11 +98,12 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { - "name": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 + "name": (IndexName,), # noqa: E501 + "dimension": (IndexDimension,), # noqa: E501 "spec": (dict,), # noqa: E501 - "metric": (str,), # noqa: E501 + "metric": (IndexMetric,), # noqa: E501 } @cached_property @@ -130,9 +127,9 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 """CreateIndexRequest - a model defined in OpenAPI Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. - spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. Serverless indexes are in public preview and are available only on AWS in the us-west-2 region. Test thoroughly before using serverless indexes in production. + name (IndexName): + dimension (IndexDimension): + spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -165,7 +162,7 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 + metric (IndexMetric): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -225,9 +222,9 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 """CreateIndexRequest - a model defined in OpenAPI Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. - spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. Serverless indexes are in public preview and are available only on AWS in the us-west-2 region. Test thoroughly before using serverless indexes in production. + name (IndexName): + dimension (IndexDimension): + spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -260,7 +257,7 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 + metric (IndexMetric): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/error_response.py b/pinecone/core/control/client/model/error_response.py similarity index 97% rename from pinecone/core/client/model/error_response.py rename to pinecone/core/control/client/model/error_response.py index 96b8bab0b..d0ca5ce6a 100644 --- a/pinecone/core/client/model/error_response.py +++ b/pinecone/core/control/client/model/error_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.error_response_error import ErrorResponseError + from pinecone.core.control.client.model.error_response_error import ErrorResponseError globals()["ErrorResponseError"] = ErrorResponseError diff --git a/pinecone/core/client/model/error_response_error.py b/pinecone/core/control/client/model/error_response_error.py similarity index 98% rename from pinecone/core/client/model/error_response_error.py rename to pinecone/core/control/client/model/error_response_error.py index f68301999..1828b047c 100644 --- a/pinecone/core/client/model/error_response_error.py +++ b/pinecone/core/control/client/model/error_response_error.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class ErrorResponseError(ModelNormal): diff --git a/pinecone/core/control/client/model/index_dimension.py b/pinecone/core/control/client/model/index_dimension.py new file mode 100644 index 000000000..b330b041c --- /dev/null +++ b/pinecone/core/control/client/model/index_dimension.py @@ -0,0 +1,301 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class IndexDimension(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = { + ("value",): { + "inclusive_maximum": 20000, + "inclusive_minimum": 1, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (int,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IndexDimension - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + + Keyword Args: + value (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IndexDimension - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + + Keyword Args: + value (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/client/model/index_list.py b/pinecone/core/control/client/model/index_list.py similarity index 97% rename from pinecone/core/client/model/index_list.py rename to pinecone/core/control/client/model/index_list.py index 250a1aa8b..80f09b786 100644 --- a/pinecone/core/client/model/index_list.py +++ b/pinecone/core/control/client/model/index_list.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.index_model import IndexModel + from pinecone.core.control.client.model.index_model import IndexModel globals()["IndexModel"] = IndexModel diff --git a/pinecone/core/control/client/model/index_metric.py b/pinecone/core/control/client/model/index_metric.py new file mode 100644 index 000000000..80ca7c26d --- /dev/null +++ b/pinecone/core/control/client/model/index_metric.py @@ -0,0 +1,294 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class IndexMetric(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ("value",): { + "COSINE": "cosine", + "EUCLIDEAN": "euclidean", + "DOTPRODUCT": "dotproduct", + }, + } + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (str,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IndexMetric - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + + Keyword Args: + value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = "cosine" + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IndexMetric - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + + Keyword Args: + value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = "cosine" + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/client/model/index_model.py b/pinecone/core/control/client/model/index_model.py similarity index 84% rename from pinecone/core/client/model/index_model.py rename to pinecone/core/control/client/model/index_model.py index 1a6fdf738..ddd669254 100644 --- a/pinecone/core/client/model/index_model.py +++ b/pinecone/core/control/client/model/index_model.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,15 +26,21 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.index_model_spec import IndexModelSpec - from pinecone.core.client.model.index_model_status import IndexModelStatus - + from pinecone.core.control.client.model.index_dimension import IndexDimension + from pinecone.core.control.client.model.index_metric import IndexMetric + from pinecone.core.control.client.model.index_model_spec import IndexModelSpec + from pinecone.core.control.client.model.index_model_status import IndexModelStatus + from pinecone.core.control.client.model.index_name import IndexName + + globals()["IndexDimension"] = IndexDimension + globals()["IndexMetric"] = IndexMetric globals()["IndexModelSpec"] = IndexModelSpec globals()["IndexModelStatus"] = IndexModelStatus + globals()["IndexName"] = IndexName class IndexModel(ModelNormal): @@ -61,24 +67,9 @@ class IndexModel(ModelNormal): as additional properties values. """ - allowed_values = { - ("metric",): { - "COSINE": "cosine", - "EUCLIDEAN": "euclidean", - "DOTPRODUCT": "dotproduct", - }, - } + allowed_values = {} - validations = { - ("name",): { - "max_length": 45, - "min_length": 1, - }, - ("dimension",): { - "inclusive_maximum": 20000, - "inclusive_minimum": 1, - }, - } + validations = {} @cached_property def additional_properties_type(): @@ -113,9 +104,9 @@ def openapi_types(): """ lazy_import() return { - "name": (str,), # noqa: E501 - "dimension": (int,), # noqa: E501 - "metric": (str,), # noqa: E501 + "name": (IndexName,), # noqa: E501 + "dimension": (IndexDimension,), # noqa: E501 + "metric": (IndexMetric,), # noqa: E501 "host": (str,), # noqa: E501 "spec": (IndexModelSpec,), # noqa: E501 "status": (IndexModelStatus,), # noqa: E501 @@ -140,18 +131,18 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. + name (IndexName): + dimension (IndexDimension): + metric (IndexMetric): host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -184,7 +175,6 @@ def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs _visited_composed_classes = (Animal,) """ - metric = kwargs.get("metric", "cosine") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) @@ -241,18 +231,18 @@ def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs ) @convert_js_args_to_python_args - def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 + def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: - name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. - dimension (int): The dimensions of the vectors to be inserted in the index. + name (IndexName): + dimension (IndexDimension): + metric (IndexMetric): host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: - metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -285,7 +275,6 @@ def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noq _visited_composed_classes = (Animal,) """ - metric = kwargs.get("metric", "cosine") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) diff --git a/pinecone/core/client/model/index_model_spec.py b/pinecone/core/control/client/model/index_model_spec.py similarity index 97% rename from pinecone/core/client/model/index_model_spec.py rename to pinecone/core/control/client/model/index_model_spec.py index 9c8e63f1b..078000b19 100644 --- a/pinecone/core/client/model/index_model_spec.py +++ b/pinecone/core/control/client/model/index_model_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,12 +26,12 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.pod_spec import PodSpec - from pinecone.core.client.model.serverless_spec import ServerlessSpec + from pinecone.core.control.client.model.pod_spec import PodSpec + from pinecone.core.control.client.model.serverless_spec import ServerlessSpec globals()["PodSpec"] = PodSpec globals()["ServerlessSpec"] = ServerlessSpec diff --git a/pinecone/core/client/model/index_model_status.py b/pinecone/core/control/client/model/index_model_status.py similarity index 98% rename from pinecone/core/client/model/index_model_status.py rename to pinecone/core/control/client/model/index_model_status.py index ffc25f114..b5417354a 100644 --- a/pinecone/core/client/model/index_model_status.py +++ b/pinecone/core/control/client/model/index_model_status.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class IndexModelStatus(ModelNormal): diff --git a/pinecone/core/control/client/model/index_name.py b/pinecone/core/control/client/model/index_name.py new file mode 100644 index 000000000..eb94ddd24 --- /dev/null +++ b/pinecone/core/control/client/model/index_name.py @@ -0,0 +1,301 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class IndexName(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = { + ("value",): { + "max_length": 45, + "min_length": 1, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (str,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IndexName - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The 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 '-'. . # noqa: E501 + + Keyword Args: + value (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 '-'. . # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IndexName - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): The 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 '-'. . # noqa: E501 + + Keyword Args: + value (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 '-'. . # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + raise PineconeApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/client/model/pod_spec.py b/pinecone/core/control/client/model/pod_spec.py similarity index 89% rename from pinecone/core/client/model/pod_spec.py rename to pinecone/core/control/client/model/pod_spec.py index 1f408af9b..7510057b7 100644 --- a/pinecone/core/client/model/pod_spec.py +++ b/pinecone/core/control/client/model/pod_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,13 +26,17 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.pod_spec_metadata_config import PodSpecMetadataConfig + from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig + from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas + from pinecone.core.control.client.model.pod_spec_shards import PodSpecShards globals()["PodSpecMetadataConfig"] = PodSpecMetadataConfig + globals()["PodSpecReplicas"] = PodSpecReplicas + globals()["PodSpecShards"] = PodSpecShards class PodSpec(ModelNormal): @@ -62,12 +66,6 @@ class PodSpec(ModelNormal): allowed_values = {} validations = { - ("replicas",): { - "inclusive_minimum": 1, - }, - ("shards",): { - "inclusive_minimum": 1, - }, ("pods",): { "inclusive_minimum": 1, }, @@ -107,8 +105,8 @@ def openapi_types(): lazy_import() return { "environment": (str,), # noqa: E501 - "replicas": (int,), # noqa: E501 - "shards": (int,), # noqa: E501 + "replicas": (PodSpecReplicas,), # noqa: E501 + "shards": (PodSpecShards,), # noqa: E501 "pod_type": (str,), # noqa: E501 "pods": (int,), # noqa: E501 "metadata_config": (PodSpecMetadataConfig,), # noqa: E501 @@ -135,15 +133,15 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, environment, replicas, shards, *args, **kwargs): # noqa: E501 """PodSpec - a model defined in OpenAPI Args: environment (str): The environment where the index is hosted. + replicas (PodSpecReplicas): + shards (PodSpecShards): Keyword Args: - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.'. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types @@ -180,8 +178,6 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ - replicas = kwargs.get("replicas", 1) - shards = kwargs.get("shards", 1) pod_type = kwargs.get("pod_type", "p1.x1") pods = kwargs.get("pods", 1) _check_type = kwargs.pop("_check_type", True) @@ -239,15 +235,15 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 ) @convert_js_args_to_python_args - def __init__(self, environment, *args, **kwargs): # noqa: E501 + def __init__(self, environment, replicas, shards, *args, **kwargs): # noqa: E501 """PodSpec - a model defined in OpenAPI Args: environment (str): The environment where the index is hosted. + replicas (PodSpecReplicas): + shards (PodSpecShards): Keyword Args: - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.'. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types @@ -284,8 +280,6 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ - replicas = kwargs.get("replicas", 1) - shards = kwargs.get("shards", 1) pod_type = kwargs.get("pod_type", "p1.x1") pods = kwargs.get("pods", 1) _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/pod_spec_metadata_config.py b/pinecone/core/control/client/model/pod_spec_metadata_config.py similarity index 98% rename from pinecone/core/client/model/pod_spec_metadata_config.py rename to pinecone/core/control/client/model/pod_spec_metadata_config.py index 1b3f35746..4847a2bae 100644 --- a/pinecone/core/client/model/pod_spec_metadata_config.py +++ b/pinecone/core/control/client/model/pod_spec_metadata_config.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class PodSpecMetadataConfig(ModelNormal): diff --git a/pinecone/core/control/client/model/pod_spec_replicas.py b/pinecone/core/control/client/model/pod_spec_replicas.py new file mode 100644 index 000000000..58aaee18e --- /dev/null +++ b/pinecone/core/control/client/model/pod_spec_replicas.py @@ -0,0 +1,292 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class PodSpecReplicas(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = { + ("value",): { + "inclusive_minimum": 1, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (int,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """PodSpecReplicas - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 + + Keyword Args: + value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = 1 + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """PodSpecReplicas - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 + + Keyword Args: + value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = 1 + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/control/client/model/pod_spec_shards.py b/pinecone/core/control/client/model/pod_spec_shards.py new file mode 100644 index 000000000..18ffa9a14 --- /dev/null +++ b/pinecone/core/control/client/model/pod_spec_shards.py @@ -0,0 +1,292 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class PodSpecShards(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = { + ("value",): { + "inclusive_minimum": 1, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (int,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """PodSpecShards - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + + Keyword Args: + value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = 1 + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """PodSpecShards - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + + Keyword Args: + value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = 1 + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/client/model/serverless_spec.py b/pinecone/core/control/client/model/serverless_spec.py similarity index 97% rename from pinecone/core/client/model/serverless_spec.py rename to pinecone/core/control/client/model/serverless_spec.py index 1415c0189..32bf9373b 100644 --- a/pinecone/core/client/model/serverless_spec.py +++ b/pinecone/core/control/client/model/serverless_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.control.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.control.client.exceptions import PineconeApiAttributeError class ServerlessSpec(ModelNormal): @@ -118,7 +118,7 @@ def _from_openapi_data(cls, cloud, region, *args, **kwargs): # noqa: E501 Args: cloud (str): The public cloud where you would like your index hosted. Serverless indexes can be hosted only in AWS at this time. - region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-west-2 region of AWS at this time. + region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-east-1,us-west-2, and eu-west-1 regions of AWS at this time. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -210,7 +210,7 @@ def __init__(self, cloud, region, *args, **kwargs): # noqa: E501 Args: cloud (str): The public cloud where you would like your index hosted. Serverless indexes can be hosted only in AWS at this time. - region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-west-2 region of AWS at this time. + region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-east-1,us-west-2, and eu-west-1 regions of AWS at this time. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/client/model_utils.py b/pinecone/core/control/client/model_utils.py similarity index 99% rename from pinecone/core/client/model_utils.py rename to pinecone/core/control/client/model_utils.py index 6874920a5..f0c9d2d70 100644 --- a/pinecone/core/client/model_utils.py +++ b/pinecone/core/control/client/model_utils.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -16,7 +16,7 @@ import re import tempfile -from pinecone.core.client.exceptions import ( +from pinecone.core.control.client.exceptions import ( PineconeApiKeyError, PineconeApiAttributeError, PineconeApiTypeError, @@ -1652,6 +1652,7 @@ def get_allof_instances(self, model_args, constant_args): """ composed_instances = [] for allof_class in self._composed_schemas["allOf"]: + try: allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) diff --git a/pinecone/core/control/client/models/__init__.py b/pinecone/core/control/client/models/__init__.py new file mode 100644 index 000000000..2e225c956 --- /dev/null +++ b/pinecone/core/control/client/models/__init__.py @@ -0,0 +1,32 @@ +# 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.control.client.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from pinecone.core.control.client.model.collection_list import CollectionList +from pinecone.core.control.client.model.collection_model import CollectionModel +from pinecone.core.control.client.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.control.client.model.configure_index_request_spec import ConfigureIndexRequestSpec +from pinecone.core.control.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod +from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest +from pinecone.core.control.client.model.create_index_request import CreateIndexRequest +from pinecone.core.control.client.model.error_response import ErrorResponse +from pinecone.core.control.client.model.error_response_error import ErrorResponseError +from pinecone.core.control.client.model.index_dimension import IndexDimension +from pinecone.core.control.client.model.index_list import IndexList +from pinecone.core.control.client.model.index_metric import IndexMetric +from pinecone.core.control.client.model.index_model import IndexModel +from pinecone.core.control.client.model.index_model_spec import IndexModelSpec +from pinecone.core.control.client.model.index_model_status import IndexModelStatus +from pinecone.core.control.client.model.index_name import IndexName +from pinecone.core.control.client.model.pod_spec import PodSpec +from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig +from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas +from pinecone.core.control.client.model.pod_spec_shards import PodSpecShards +from pinecone.core.control.client.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/client/rest.py b/pinecone/core/control/client/rest.py similarity index 99% rename from pinecone/core/client/rest.py rename to pinecone/core/control/client/rest.py index 28fd1ff96..fc58e24b9 100644 --- a/pinecone/core/client/rest.py +++ b/pinecone/core/control/client/rest.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -18,7 +18,7 @@ import urllib3 -from pinecone.core.client.exceptions import ( +from pinecone.core.control.client.exceptions import ( PineconeApiException, UnauthorizedException, ForbiddenException, @@ -44,6 +44,7 @@ class bcolors: class RESTResponse(io.IOBase): + def __init__(self, resp): self.urllib3_response = resp self.status = resp.status @@ -60,6 +61,7 @@ def getheader(self, name, default=None): class RESTClientObject(object): + def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 diff --git a/pinecone/core/data/__init__.py b/pinecone/core/data/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/pinecone/core/data/client/__init__.py b/pinecone/core/data/client/__init__.py new file mode 100644 index 000000000..e7904f3e0 --- /dev/null +++ b/pinecone/core/data/client/__init__.py @@ -0,0 +1,28 @@ +# 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 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from pinecone.core.data.client.api_client import ApiClient + +# import Configuration +from pinecone.core.data.client.configuration import Configuration + +# import exceptions +from pinecone.core.data.client.exceptions import PineconeException +from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiTypeError +from pinecone.core.data.client.exceptions import PineconeApiValueError +from pinecone.core.data.client.exceptions import PineconeApiKeyError +from pinecone.core.data.client.exceptions import PineconeApiException diff --git a/pinecone/core/client/api/__init__.py b/pinecone/core/data/client/api/__init__.py similarity index 74% rename from pinecone/core/client/api/__init__.py rename to pinecone/core/data/client/api/__init__.py index 47c2114b2..f8da73fe3 100644 --- a/pinecone/core/client/api/__init__.py +++ b/pinecone/core/data/client/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.client.apis import DataPlaneApi +# from pinecone.core.data.client.apis import DataPlaneApi diff --git a/pinecone/core/client/api/data_plane_api.py b/pinecone/core/data/client/api/data_plane_api.py similarity index 94% rename from pinecone/core/client/api/data_plane_api.py rename to pinecone/core/data/client/api/data_plane_api.py index d8c86326e..26d91d709 100644 --- a/pinecone/core/client/api/data_plane_api.py +++ b/pinecone/core/data/client/api/data_plane_api.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.data.client.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, @@ -21,17 +21,17 @@ none_type, validate_and_convert_types, ) -from pinecone.core.client.model.delete_request import DeleteRequest -from pinecone.core.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.client.model.fetch_response import FetchResponse -from pinecone.core.client.model.list_response import ListResponse -from pinecone.core.client.model.query_request import QueryRequest -from pinecone.core.client.model.query_response import QueryResponse -from pinecone.core.client.model.rpc_status import RpcStatus -from pinecone.core.client.model.update_request import UpdateRequest -from pinecone.core.client.model.upsert_request import UpsertRequest -from pinecone.core.client.model.upsert_response import UpsertResponse +from pinecone.core.data.client.model.delete_request import DeleteRequest +from pinecone.core.data.client.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.data.client.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.data.client.model.fetch_response import FetchResponse +from pinecone.core.data.client.model.list_response import ListResponse +from pinecone.core.data.client.model.query_request import QueryRequest +from pinecone.core.data.client.model.query_response import QueryResponse +from pinecone.core.data.client.model.rpc_status import RpcStatus +from pinecone.core.data.client.model.update_request import UpdateRequest +from pinecone.core.data.client.model.upsert_request import UpsertRequest +from pinecone.core.data.client.model.upsert_response import UpsertResponse class DataPlaneApi(object): @@ -49,7 +49,7 @@ def __init__(self, api_client=None): def __alt_delete(self, **kwargs): """Delete vectors # noqa: E501 - DEPRECATED. Use [`POST /delete`](https://docs.pinecone.io/reference/delete) instead. # noqa: E501 + DEPRECATED. Use [`POST /delete`](https://docs.pinecone.io/reference/api/data-plane/delete) instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -148,7 +148,7 @@ def __alt_delete(self, **kwargs): def __alt_describe_index_stats(self, **kwargs): """Get index stats # noqa: E501 - DEPRECATED. Use [`POST /describe_index_stats`](https://docs.pinecone.io/reference/describe_index_stats) instead. # noqa: E501 + DEPRECATED. Use [`POST /describe_index_stats`](https://docs.pinecone.io/reference/api/data-plane/describeindexstats) instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -220,7 +220,7 @@ def __alt_describe_index_stats(self, **kwargs): def __delete(self, delete_request, **kwargs): """Delete vectors # noqa: E501 - The `delete` operation deletes vectors, by id, from a single namespace. For guidance and examples, see [Delete data](https://docs.pinecone.io/docs/delete-data). # noqa: E501 + The `delete` operation deletes vectors, by id, from a single namespace. For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -306,7 +306,7 @@ def __delete(self, delete_request, **kwargs): def __describe_index_stats(self, describe_index_stats_request, **kwargs): """Get index stats # noqa: E501 - The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace and the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. For pod-based indexes, the index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://www.pinecone.io/docs/api/operation/describe_index/). # noqa: E501 + The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. For pod-based indexes, the index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -392,7 +392,7 @@ def __describe_index_stats(self, describe_index_stats_request, **kwargs): def __fetch(self, ids, **kwargs): """Fetch vectors # noqa: E501 - The `fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. For guidance and examples, see [Fetch data](https://docs.pinecone.io/reference/fetch). # noqa: E501 + The `fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. 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 @@ -490,7 +490,7 @@ def __fetch(self, ids, **kwargs): def __list(self, **kwargs): """List vector IDs # noqa: E501 - The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. `list` returns up to 100 IDs at a time by default in sorted order (bitwise/\"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [Get record IDs](https://docs.pinecone.io/docs/get-record-ids). **Note:** `list` is supported only for serverless indexes. # noqa: E501 + The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. `list` returns up to 100 IDs at a time by default in sorted order (bitwise \"C\" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list` is supported only for serverless indexes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -500,7 +500,7 @@ def __list(self, **kwargs): Keyword Args: prefix (str): The vector IDs to fetch. Does not accept values containing spaces.. [optional] - limit (int): Max number of ids to return.. [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 @@ -592,7 +592,7 @@ def __list(self, **kwargs): def __query(self, query_request, **kwargs): """Query vectors # noqa: E501 - The `query` operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. For guidance and examples, see [Query data](https://docs.pinecone.io/docs/query-data). # noqa: E501 + The `query` operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. 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 @@ -678,7 +678,7 @@ def __query(self, query_request, **kwargs): def __update(self, update_request, **kwargs): """Update a vector # noqa: E501 - The `update` operation updates a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. For guidance and examples, see [Update data](https://docs.pinecone.io/reference/update). # noqa: E501 + The `update` operation updates a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -764,7 +764,7 @@ def __update(self, update_request, **kwargs): def __upsert(self, upsert_request, **kwargs): """Upsert vectors # noqa: E501 - The `upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. For guidance and examples, see [Upsert data](https://docs.pinecone.io/docs/upsert-data). # noqa: E501 + The `upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. 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 diff --git a/pinecone/core/client/api_client.py b/pinecone/core/data/client/api_client.py similarity index 98% rename from pinecone/core/client/api_client.py rename to pinecone/core/data/client/api_client.py index 5d7999e4f..29e1c4f57 100644 --- a/pinecone/core/client/api_client.py +++ b/pinecone/core/data/client/api_client.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -20,10 +20,10 @@ from urllib3.fields import RequestField -from pinecone.core.client import rest -from pinecone.core.client.configuration import Configuration -from pinecone.core.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException -from pinecone.core.client.model_utils import ( +from pinecone.core.data.client import rest +from pinecone.core.data.client.configuration import Configuration +from pinecone.core.data.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException +from pinecone.core.data.client.model_utils import ( ModelNormal, ModelSimple, ModelComposed, @@ -132,6 +132,7 @@ def __call_api( _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None, ): + config = self.configuration # header parameters @@ -770,6 +771,7 @@ def __call__(self, *args, **kwargs): return self.callable(self, *args, **kwargs) def call_with_http_info(self, **kwargs): + try: index = ( self.api_client.configuration.server_operation_index.get( diff --git a/pinecone/core/client/apis/__init__.py b/pinecone/core/data/client/apis/__init__.py similarity index 75% rename from pinecone/core/client/apis/__init__.py rename to pinecone/core/data/client/apis/__init__.py index 39c5562e9..d3cf0b6eb 100644 --- a/pinecone/core/client/apis/__init__.py +++ b/pinecone/core/data/client/apis/__init__.py @@ -13,5 +13,4 @@ # sys.setrecursionlimit(n) # Import APIs into API package: -from pinecone.core.client.api.data_plane_api import DataPlaneApi -from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.data.client.api.data_plane_api import DataPlaneApi diff --git a/pinecone/core/data/client/configuration.py b/pinecone/core/data/client/configuration.py new file mode 100644 index 000000000..01f36d2b6 --- /dev/null +++ b/pinecone/core/data/client/configuration.py @@ -0,0 +1,487 @@ +""" + Pinecone Data Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +from http import client as http_client +from pinecone.core.data.client.exceptions import PineconeApiValueError + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum", + "maxLength", + "minLength", + "pattern", + "maxItems", + "minItems", +} + + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + + conf = pinecone.core.data.client.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} + ) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 + """ + + _default = None + + def __init__( + self, + host=None, + api_key=None, + api_key_prefix=None, + access_token=None, + username=None, + password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + server_index=None, + server_variables=None, + server_operation_index=None, + server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor""" + self._base_path = "https://unknown" 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.access_token = access_token + 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.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("pinecone.core.data.client") + 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 get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers(basic_auth=username + ":" + password).get("authorization") + + 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 to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return ( + "Python SDK Debug Report:\n" + "OS: {env}\n" + "Python Version: {pyversion}\n" + "Version of the API: 2024-04\n" + "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) + ) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + "url": "https://{index_host}", + "description": "No description provided", + "variables": { + "index_host": { + "description": "host of the index", + "default_value": "unknown", + } + }, + } + ] + + 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 diff --git a/pinecone/core/data/client/exceptions.py b/pinecone/core/data/client/exceptions.py new file mode 100644 index 000000000..55f21fdc7 --- /dev/null +++ b/pinecone/core/data/client/exceptions.py @@ -0,0 +1,156 @@ +""" + Pinecone Data Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +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): + """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): + """ + 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): + """ + 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): + """ + 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): + 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})\n" "Reason: {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): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=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/core/data/client/model/__init__.py b/pinecone/core/data/client/model/__init__.py new file mode 100644 index 000000000..cfe32b784 --- /dev/null +++ b/pinecone/core/data/client/model/__init__.py @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from {{packageName}.models import ModelA, ModelB diff --git a/pinecone/core/client/model/delete_request.py b/pinecone/core/data/client/model/delete_request.py similarity index 93% rename from pinecone/core/client/model/delete_request.py rename to pinecone/core/data/client/model/delete_request.py index c1eb3d7a2..d31507df8 100644 --- a/pinecone/core/client/model/delete_request.py +++ b/pinecone/core/data/client/model/delete_request.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class DeleteRequest(ModelNormal): @@ -150,7 +150,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -240,7 +240,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/describe_index_stats_request.py b/pinecone/core/data/client/model/describe_index_stats_request.py similarity index 94% rename from pinecone/core/client/model/describe_index_stats_request.py rename to pinecone/core/data/client/model/describe_index_stats_request.py index dffc9965d..e56c01dc8 100644 --- a/pinecone/core/client/model/describe_index_stats_request.py +++ b/pinecone/core/data/client/model/describe_index_stats_request.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class DescribeIndexStatsRequest(ModelNormal): @@ -139,7 +139,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -226,7 +226,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support filtering `describe_index_stats` by metadata.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/describe_index_stats_response.py b/pinecone/core/data/client/model/describe_index_stats_response.py similarity index 90% rename from pinecone/core/client/model/describe_index_stats_response.py rename to pinecone/core/data/client/model/describe_index_stats_response.py index 386576288..79db67494 100644 --- a/pinecone/core/client/model/describe_index_stats_response.py +++ b/pinecone/core/data/client/model/describe_index_stats_response.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.namespace_summary import NamespaceSummary + from pinecone.core.data.client.model.namespace_summary import NamespaceSummary globals()["NamespaceSummary"] = NamespaceSummary @@ -155,8 +155,8 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%.. [optional] # noqa: E501 - total_vector_count (int): [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -245,8 +245,8 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%.. [optional] # noqa: E501 - total_vector_count (int): [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/fetch_response.py b/pinecone/core/data/client/model/fetch_response.py similarity index 97% rename from pinecone/core/client/model/fetch_response.py rename to pinecone/core/data/client/model/fetch_response.py index 00cf0d6a1..afa1a4959 100644 --- a/pinecone/core/client/model/fetch_response.py +++ b/pinecone/core/data/client/model/fetch_response.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,12 +26,12 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.usage import Usage - from pinecone.core.client.model.vector import Vector + from pinecone.core.data.client.model.usage import Usage + from pinecone.core.data.client.model.vector import Vector globals()["Usage"] = Usage globals()["Vector"] = Vector diff --git a/pinecone/core/client/model/list_item.py b/pinecone/core/data/client/model/list_item.py similarity index 98% rename from pinecone/core/client/model/list_item.py rename to pinecone/core/data/client/model/list_item.py index 687c061b6..2955ea0da 100644 --- a/pinecone/core/client/model/list_item.py +++ b/pinecone/core/data/client/model/list_item.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class ListItem(ModelNormal): diff --git a/pinecone/core/client/model/list_response.py b/pinecone/core/data/client/model/list_response.py similarity index 96% rename from pinecone/core/client/model/list_response.py rename to pinecone/core/data/client/model/list_response.py index 9a2b30653..8b331afa7 100644 --- a/pinecone/core/client/model/list_response.py +++ b/pinecone/core/data/client/model/list_response.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,13 +26,13 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.list_item import ListItem - from pinecone.core.client.model.pagination import Pagination - from pinecone.core.client.model.usage import Usage + from pinecone.core.data.client.model.list_item import ListItem + from pinecone.core.data.client.model.pagination import Pagination + from pinecone.core.data.client.model.usage import Usage globals()["ListItem"] = ListItem globals()["Pagination"] = Pagination diff --git a/pinecone/core/client/model/namespace_summary.py b/pinecone/core/data/client/model/namespace_summary.py similarity index 98% rename from pinecone/core/client/model/namespace_summary.py rename to pinecone/core/data/client/model/namespace_summary.py index 9105515ec..d0100655a 100644 --- a/pinecone/core/client/model/namespace_summary.py +++ b/pinecone/core/data/client/model/namespace_summary.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class NamespaceSummary(ModelNormal): diff --git a/pinecone/core/client/model/pagination.py b/pinecone/core/data/client/model/pagination.py similarity index 98% rename from pinecone/core/client/model/pagination.py rename to pinecone/core/data/client/model/pagination.py index 5f0836dd4..58231c1e7 100644 --- a/pinecone/core/client/model/pagination.py +++ b/pinecone/core/data/client/model/pagination.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class Pagination(ModelNormal): diff --git a/pinecone/core/client/model/protobuf_any.py b/pinecone/core/data/client/model/protobuf_any.py similarity index 98% rename from pinecone/core/client/model/protobuf_any.py rename to pinecone/core/data/client/model/protobuf_any.py index 3a0c40422..844b862a0 100644 --- a/pinecone/core/client/model/protobuf_any.py +++ b/pinecone/core/data/client/model/protobuf_any.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class ProtobufAny(ModelNormal): diff --git a/pinecone/core/client/model/protobuf_null_value.py b/pinecone/core/data/client/model/protobuf_null_value.py similarity index 91% rename from pinecone/core/client/model/protobuf_null_value.py rename to pinecone/core/data/client/model/protobuf_null_value.py index 8edc2ac4d..ced00cbf9 100644 --- a/pinecone/core/client/model/protobuf_null_value.py +++ b/pinecone/core/data/client/model/protobuf_null_value.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class ProtobufNullValue(ModelSimple): @@ -119,10 +119,10 @@ def __init__(self, *args, **kwargs): Note that value can be passed either in args or in kwargs, but not in both. Args: - args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + 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`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + 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. @@ -207,10 +207,10 @@ def _from_openapi_data(cls, *args, **kwargs): Note that value can be passed either in args or in kwargs, but not in both. Args: - args[0] (str): `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + 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`. - NULL_VALUE: Null value.. if omitted defaults to "NULL_VALUE", must be one of ["NULL_VALUE", ] # noqa: E501 + 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. diff --git a/pinecone/core/client/model/query_request.py b/pinecone/core/data/client/model/query_request.py similarity index 95% rename from pinecone/core/client/model/query_request.py rename to pinecone/core/data/client/model/query_request.py index 8f410dbc8..6fe6f52cf 100644 --- a/pinecone/core/client/model/query_request.py +++ b/pinecone/core/data/client/model/query_request.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,12 +26,12 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.query_vector import QueryVector - from pinecone.core.client.model.sparse_values import SparseValues + from pinecone.core.data.client.model.query_vector import QueryVector + from pinecone.core.data.client.model.sparse_values import SparseValues globals()["QueryVector"] = QueryVector globals()["SparseValues"] = SparseValues @@ -179,7 +179,7 @@ def _from_openapi_data(cls, top_k, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-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 @@ -277,7 +277,7 @@ def __init__(self, top_k, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) namespace (str): The namespace to query.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): The filter to apply. You can use vector metadata to limit your search. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata).. [optional] # noqa: E501 include_values (bool): Indicates whether vector values are included in the response.. [optional] if omitted the server will use the default value of False # noqa: E501 include_metadata (bool): Indicates whether metadata is included in the response as well as the ids.. [optional] if omitted the server will use the default value of False # noqa: E501 queries ([QueryVector]): DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.. [optional] # noqa: E501 diff --git a/pinecone/core/client/model/query_response.py b/pinecone/core/data/client/model/query_response.py similarity index 96% rename from pinecone/core/client/model/query_response.py rename to pinecone/core/data/client/model/query_response.py index 06c9d0c17..1c6425c13 100644 --- a/pinecone/core/client/model/query_response.py +++ b/pinecone/core/data/client/model/query_response.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,13 +26,13 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.scored_vector import ScoredVector - from pinecone.core.client.model.single_query_results import SingleQueryResults - from pinecone.core.client.model.usage import Usage + from pinecone.core.data.client.model.scored_vector import ScoredVector + from pinecone.core.data.client.model.single_query_results import SingleQueryResults + from pinecone.core.data.client.model.usage import Usage globals()["ScoredVector"] = ScoredVector globals()["SingleQueryResults"] = SingleQueryResults diff --git a/pinecone/core/client/model/query_vector.py b/pinecone/core/data/client/model/query_vector.py similarity index 97% rename from pinecone/core/client/model/query_vector.py rename to pinecone/core/data/client/model/query_vector.py index f7ca7337e..2f6dec113 100644 --- a/pinecone/core/client/model/query_vector.py +++ b/pinecone/core/data/client/model/query_vector.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues + from pinecone.core.data.client.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/client/model/rpc_status.py b/pinecone/core/data/client/model/rpc_status.py similarity index 97% rename from pinecone/core/client/model/rpc_status.py rename to pinecone/core/data/client/model/rpc_status.py index a2f422bf8..3be73765d 100644 --- a/pinecone/core/client/model/rpc_status.py +++ b/pinecone/core/data/client/model/rpc_status.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.protobuf_any import ProtobufAny + from pinecone.core.data.client.model.protobuf_any import ProtobufAny globals()["ProtobufAny"] = ProtobufAny diff --git a/pinecone/core/client/model/scored_vector.py b/pinecone/core/data/client/model/scored_vector.py similarity index 97% rename from pinecone/core/client/model/scored_vector.py rename to pinecone/core/data/client/model/scored_vector.py index 60cad1cee..0cfe503fa 100644 --- a/pinecone/core/client/model/scored_vector.py +++ b/pinecone/core/data/client/model/scored_vector.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues + from pinecone.core.data.client.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/client/model/single_query_results.py b/pinecone/core/data/client/model/single_query_results.py similarity index 97% rename from pinecone/core/client/model/single_query_results.py rename to pinecone/core/data/client/model/single_query_results.py index 88776062b..34fb7a489 100644 --- a/pinecone/core/client/model/single_query_results.py +++ b/pinecone/core/data/client/model/single_query_results.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.scored_vector import ScoredVector + from pinecone.core.data.client.model.scored_vector import ScoredVector globals()["ScoredVector"] = ScoredVector diff --git a/pinecone/core/client/model/sparse_values.py b/pinecone/core/data/client/model/sparse_values.py similarity index 95% rename from pinecone/core/client/model/sparse_values.py rename to pinecone/core/data/client/model/sparse_values.py index b96503522..d0f839d64 100644 --- a/pinecone/core/client/model/sparse_values.py +++ b/pinecone/core/data/client/model/sparse_values.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class SparseValues(ModelNormal): @@ -114,8 +114,8 @@ def _from_openapi_data(cls, indices, values, *args, **kwargs): # noqa: E501 """SparseValues - a model defined in OpenAPI Args: - indices ([int]): - values ([float]): + 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 @@ -206,8 +206,8 @@ def __init__(self, indices, values, *args, **kwargs): # noqa: E501 """SparseValues - a model defined in OpenAPI Args: - indices ([int]): - values ([float]): + 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 diff --git a/pinecone/core/client/model/update_request.py b/pinecone/core/data/client/model/update_request.py similarity index 94% rename from pinecone/core/client/model/update_request.py rename to pinecone/core/data/client/model/update_request.py index da569e576..1b92db2d2 100644 --- a/pinecone/core/client/model/update_request.py +++ b/pinecone/core/data/client/model/update_request.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues + from pinecone.core.data.client.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues @@ -166,8 +166,8 @@ def _from_openapi_data(cls, id, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) values ([float]): Vector data.. [optional] # noqa: E501 sparse_values (SparseValues): [optional] # noqa: E501 - set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 - namespace (str): Namespace name where to update the vector.. [optional] # noqa: E501 + set_metadata ({str: (bool, date, datetime, 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) @@ -260,8 +260,8 @@ def __init__(self, id, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) values ([float]): Vector data.. [optional] # noqa: E501 sparse_values (SparseValues): [optional] # noqa: E501 - set_metadata ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Metadata to *set* for the vector.. [optional] # noqa: E501 - namespace (str): Namespace name where to update the vector.. [optional] # noqa: E501 + set_metadata ({str: (bool, date, datetime, 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) diff --git a/pinecone/core/client/model/upsert_request.py b/pinecone/core/data/client/model/upsert_request.py similarity index 96% rename from pinecone/core/client/model/upsert_request.py rename to pinecone/core/data/client/model/upsert_request.py index 72ae3cbdd..78d8b91e3 100644 --- a/pinecone/core/client/model/upsert_request.py +++ b/pinecone/core/data/client/model/upsert_request.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.vector import Vector + from pinecone.core.data.client.model.vector import Vector globals()["Vector"] = Vector @@ -154,7 +154,7 @@ def _from_openapi_data(cls, vectors, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - namespace (str): This is the namespace name where you upsert vectors.. [optional] # noqa: E501 + namespace (str): The namespace where you upsert vectors.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -245,7 +245,7 @@ def __init__(self, vectors, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - namespace (str): This is the namespace name where you upsert vectors.. [optional] # noqa: E501 + namespace (str): The namespace where you upsert vectors.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/client/model/upsert_response.py b/pinecone/core/data/client/model/upsert_response.py similarity index 98% rename from pinecone/core/client/model/upsert_response.py rename to pinecone/core/data/client/model/upsert_response.py index 5e3008284..b4376c528 100644 --- a/pinecone/core/client/model/upsert_response.py +++ b/pinecone/core/data/client/model/upsert_response.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class UpsertResponse(ModelNormal): diff --git a/pinecone/core/client/model/usage.py b/pinecone/core/data/client/model/usage.py similarity index 98% rename from pinecone/core/client/model/usage.py rename to pinecone/core/data/client/model/usage.py index 45b4eca2d..34ab7b185 100644 --- a/pinecone/core/client/model/usage.py +++ b/pinecone/core/data/client/model/usage.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,7 +26,7 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError class Usage(ModelNormal): diff --git a/pinecone/core/client/model/vector.py b/pinecone/core/data/client/model/vector.py similarity index 97% rename from pinecone/core/client/model/vector.py rename to pinecone/core/data/client/model/vector.py index f7f799195..f617fbef7 100644 --- a/pinecone/core/client/model/vector.py +++ b/pinecone/core/data/client/model/vector.py @@ -1,9 +1,9 @@ """ - Pinecone Control Plane API + Pinecone Data Plane API Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: v1 + The version of the OpenAPI document: 2024-04 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.client.model_utils import ( # noqa: F401 +from pinecone.core.data.client.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -26,11 +26,11 @@ validate_get_composed_info, ) from ..model_utils import OpenApiModel -from pinecone.core.client.exceptions import PineconeApiAttributeError +from pinecone.core.data.client.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.client.model.sparse_values import SparseValues + from pinecone.core.data.client.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/data/client/model_utils.py b/pinecone/core/data/client/model_utils.py new file mode 100644 index 000000000..abb0094a3 --- /dev/null +++ b/pinecone/core/data/client/model_utils.py @@ -0,0 +1,1886 @@ +""" + Pinecone Data Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import inspect +import io +import os +import pprint +import re +import tempfile + +from pinecone.core.data.client.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): + 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) != 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) + + 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 isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + # elif isinstance(input_value, datetime): + # # this must be higher than the date check because + # # isinstance(datetime_instance, date) == True + # return datetime + # elif isinstance(input_value, date): + # return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if isinstance(input_values, list) and not set(input_values).issubset(set(these_allowed_values)): + invalid_values = (", ".join(map(str, set(input_values) - set(these_allowed_values))),) + raise 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 == 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) != str: + raise get_type_error(inner_key, inner_path, valid_classes, key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration, + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: ( + (item[0], model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], "_data_store") + else item + ), + value.items(), + ) + ) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, "_data_store"): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = "value" + if key_type: + key_or_value = "key" + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = "Invalid type for variable '{0}'. Required {1} type {2} and " "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed""" + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return "is {0}".format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas["allOf"]: + + try: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise 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/core/data/client/models/__init__.py b/pinecone/core/data/client/models/__init__.py new file mode 100644 index 000000000..459eddd4e --- /dev/null +++ b/pinecone/core/data/client/models/__init__.py @@ -0,0 +1,33 @@ +# 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.data.client.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from pinecone.core.data.client.model.delete_request import DeleteRequest +from pinecone.core.data.client.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.data.client.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.data.client.model.fetch_response import FetchResponse +from pinecone.core.data.client.model.list_item import ListItem +from pinecone.core.data.client.model.list_response import ListResponse +from pinecone.core.data.client.model.namespace_summary import NamespaceSummary +from pinecone.core.data.client.model.pagination import Pagination +from pinecone.core.data.client.model.protobuf_any import ProtobufAny +from pinecone.core.data.client.model.protobuf_null_value import ProtobufNullValue +from pinecone.core.data.client.model.query_request import QueryRequest +from pinecone.core.data.client.model.query_response import QueryResponse +from pinecone.core.data.client.model.query_vector import QueryVector +from pinecone.core.data.client.model.rpc_status import RpcStatus +from pinecone.core.data.client.model.scored_vector import ScoredVector +from pinecone.core.data.client.model.single_query_results import SingleQueryResults +from pinecone.core.data.client.model.sparse_values import SparseValues +from pinecone.core.data.client.model.update_request import UpdateRequest +from pinecone.core.data.client.model.upsert_request import UpsertRequest +from pinecone.core.data.client.model.upsert_response import UpsertResponse +from pinecone.core.data.client.model.usage import Usage +from pinecone.core.data.client.model.vector import Vector diff --git a/pinecone/core/data/client/rest.py b/pinecone/core/data/client/rest.py new file mode 100644 index 000000000..0919f6ba9 --- /dev/null +++ b/pinecone/core/data/client/rest.py @@ -0,0 +1,404 @@ +""" + Pinecone Data Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-04 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import io +import json +import logging +import re +import ssl +import os +from urllib.parse import urlencode + +import urllib3 + +from pinecone.core.data.client.exceptions import ( + PineconeApiException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException, + 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__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.headers.get(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # 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. + """ + 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) + if ("Content-Type" not in headers) or (re.search("json", headers["Content-Type"], re.IGNORECASE)): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + elif headers["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 headers["Content-Type"] == "multipart/form-data": + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers["Content-Type"] + 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: + r = self.pool_manager.request( + method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers + ) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise PineconeApiException(status=0, reason=msg) + + if os.environ.get("PINECONE_DEBUG_CURL"): + o = RESTResponse(r) + + 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) + + # log response body + logger.debug("response body: %s", r.data) + + 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 + + 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, + ) From f84cce5c63e13af72bf9a6dce2ffd54da167adbf Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 11:54:20 -0400 Subject: [PATCH 05/13] WIP on fixing import paths and tests --- Makefile | 4 + codegen/build-oas.sh | 33 +- pinecone/__init__.py | 2 +- pinecone/config/config.py | 25 +- pinecone/config/openapi.py | 12 +- pinecone/config/pinecone_config.py | 7 +- pinecone/control/index_host_store.py | 6 +- pinecone/control/pinecone.py | 78 ++++- pinecone/core/control/client/__init__.py | 2 +- pinecone/core/control/client/api/__init__.py | 2 +- .../core/control/client/api/inference_api.py | 121 +++++++ .../control/client/api/manage_indexes_api.py | 77 +---- pinecone/core/control/client/api_client.py | 10 +- pinecone/core/control/client/apis/__init__.py | 3 +- pinecone/core/control/client/configuration.py | 4 +- pinecone/core/control/client/exceptions.py | 2 +- .../control/client/model/collection_list.py | 2 +- .../control/client/model/collection_model.py | 2 +- .../client/model/configure_index_request.py | 2 +- .../model/configure_index_request_spec.py | 2 +- .../model/configure_index_request_spec_pod.py | 22 +- .../client/model/create_collection_request.py | 2 +- .../client/model/create_index_request.py | 53 +-- .../{index_dimension.py => embed_request.py} | 173 +++++----- ...spec_shards.py => embed_request_inputs.py} | 144 ++++----- .../client/model/embed_request_parameters.py | 274 ++++++++++++++++ .../core/control/client/model/embedding.py | 270 ++++++++++++++++ .../control/client/model/embeddings_list.py | 288 +++++++++++++++++ .../client/model/embeddings_list_usage.py | 270 ++++++++++++++++ .../core/control/client/model/index_list.py | 2 +- .../core/control/client/model/index_metric.py | 294 ----------------- .../core/control/client/model/index_model.py | 51 +-- .../control/client/model/index_model_spec.py | 2 +- .../client/model/index_model_status.py | 2 +- .../core/control/client/model/index_name.py | 301 ------------------ .../core/control/client/model/index_spec.py | 267 ++++++++++++++++ ...rror_response.py => inline_response401.py} | 18 +- ...e_error.py => inline_response401_error.py} | 8 +- .../core/control/client/model/pod_spec.py | 36 +-- .../client/model/pod_spec_metadata_config.py | 2 +- .../control/client/model/pod_spec_replicas.py | 292 ----------------- .../control/client/model/serverless_spec.py | 2 +- pinecone/core/control/client/model_utils.py | 2 +- .../core/control/client/models/__init__.py | 16 +- pinecone/core/control/client/rest.py | 2 +- pinecone/core/data/client/__init__.py | 2 +- .../core/data/client/api/data_plane_api.py | 2 +- pinecone/core/data/client/api_client.py | 2 +- pinecone/core/data/client/configuration.py | 4 +- pinecone/core/data/client/exceptions.py | 2 +- .../core/data/client/model/delete_request.py | 6 +- .../model/describe_index_stats_request.py | 2 +- .../model/describe_index_stats_response.py | 6 +- .../core/data/client/model/fetch_response.py | 2 +- pinecone/core/data/client/model/list_item.py | 2 +- .../core/data/client/model/list_response.py | 2 +- .../data/client/model/namespace_summary.py | 2 +- pinecone/core/data/client/model/pagination.py | 2 +- .../core/data/client/model/protobuf_any.py | 2 +- .../data/client/model/protobuf_null_value.py | 2 +- .../core/data/client/model/query_request.py | 2 +- .../core/data/client/model/query_response.py | 2 +- .../core/data/client/model/query_vector.py | 2 +- pinecone/core/data/client/model/rpc_status.py | 2 +- .../core/data/client/model/scored_vector.py | 2 +- .../data/client/model/single_query_results.py | 2 +- .../core/data/client/model/sparse_values.py | 2 +- .../core/data/client/model/update_request.py | 2 +- .../core/data/client/model/upsert_request.py | 2 +- .../core/data/client/model/upsert_response.py | 2 +- pinecone/core/data/client/model/usage.py | 2 +- pinecone/core/data/client/model/vector.py | 2 +- pinecone/core/data/client/model_utils.py | 2 +- pinecone/core/data/client/rest.py | 2 +- .../core/grpc/protos/vector_service_pb2.py | 8 +- .../core/grpc/protos/vector_service_pb2.pyi | 175 +++++++--- pinecone/data/index.py | 51 ++- pinecone/data/sparse_vector_factory.py | 8 +- pinecone/data/vector_factory.py | 9 +- .../{exceptions.py => exceptions/__init__.py} | 23 +- pinecone/exceptions/exceptions.py | 16 + pinecone/exceptions/openapi_exceptions.py | 150 +++++++++ pinecone/grpc/base.py | 29 +- pinecone/grpc/future.py | 2 +- pinecone/grpc/index_grpc.py | 76 ++++- pinecone/grpc/sparse_values_factory.py | 6 +- pinecone/grpc/utils.py | 13 +- pinecone/grpc/vector_factory_grpc.py | 27 +- pinecone/models/__init__.py | 7 +- pinecone/models/collection_list.py | 4 +- pinecone/models/index_list.py | 2 +- pinecone/utils/__init__.py | 5 +- pinecone/utils/check_kwargs.py | 5 +- pinecone/utils/convert_to_list.py | 2 +- pinecone/utils/setup_openapi_client.py | 18 +- pinecone/utils/user_agent.py | 5 +- .../data/test_openapi_configuration.py | 2 +- tests/unit/models/test_collection_list.py | 2 +- tests/unit/models/test_index_list.py | 2 +- tests/unit/test_config.py | 4 +- tests/unit/test_config_builder.py | 2 +- tests/unit/test_control.py | 23 +- tests/unit/utils/test_setup_openapi_client.py | 4 +- 103 files changed, 2505 insertions(+), 1432 deletions(-) create mode 100644 pinecone/core/control/client/api/inference_api.py rename pinecone/core/control/client/model/{index_dimension.py => embed_request.py} (76%) rename pinecone/core/control/client/model/{pod_spec_shards.py => embed_request_inputs.py} (78%) create mode 100644 pinecone/core/control/client/model/embed_request_parameters.py create mode 100644 pinecone/core/control/client/model/embedding.py create mode 100644 pinecone/core/control/client/model/embeddings_list.py create mode 100644 pinecone/core/control/client/model/embeddings_list_usage.py delete mode 100644 pinecone/core/control/client/model/index_metric.py delete mode 100644 pinecone/core/control/client/model/index_name.py create mode 100644 pinecone/core/control/client/model/index_spec.py rename pinecone/core/control/client/model/{error_response.py => inline_response401.py} (95%) rename pinecone/core/control/client/model/{error_response_error.py => inline_response401_error.py} (98%) delete mode 100644 pinecone/core/control/client/model/pod_spec_replicas.py rename pinecone/{exceptions.py => exceptions/__init__.py} (61%) create mode 100644 pinecone/exceptions/exceptions.py create mode 100644 pinecone/exceptions/openapi_exceptions.py diff --git a/Makefile b/Makefile index 45e13cefc..b908e931d 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,10 @@ test-unit: @echo "Running tests..." poetry run pytest --cov=pinecone --timeout=120 tests/unit +test-integration: + @echo "Running integration tests..." + PINECONE_ENVIRONMENT="us-east4-gcp" SPEC='{"serverless": {"cloud": "aws", "region": "us-east-1" }}' DIMENSION=2 METRIC='cosine' GITHUB_BUILD_NUMBER='local' poetry run pytest tests/integration + test-grpc-unit: @echo "Running tests..." poetry run pytest --cov=pinecone --timeout=120 tests/unit_grpc diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 9173164b2..1f1203f51 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -1,6 +1,6 @@ #!/bin/bash -version='2024-04' +version='2024-07' rm -rf build mkdir build @@ -22,8 +22,8 @@ verify_spec_version() { exit 1 fi - if [ ! -d "codegen/apis/static/$version" ]; then - echo "Version $version does not exist in static dir" + if [ ! -d "codegen/apis/_build/$version" ]; then + echo "Version $version does not exist in apis build dir" exit 1 fi } @@ -62,11 +62,24 @@ generate_client() { --template-dir "/workspace/$template_dir" } +# Adjust exception import paths in generated code +adjust_exception_imports() { + local client_dir=$1 + local exception_dir=$2 + + find pinecone/core -name "*.py" -exec sed -i 's/from pinecone\.core\.control\.client\.exceptions/from pinecone\.exceptions/g' {} + + + + # Adjust import paths in exceptions + sed -i '' -e 's/from pinecone\.core\.exceptions/from pinecone.core.control.exceptions/g' $exception_dir/__init__.py + sed -i '' -e 's/from pinecone\.core\.exceptions/from pinecone.core.data.exceptions/g' $exception_dir/__init__.py +} + update_apis_repo verify_spec_version $version # Generate data plane client -data_oas="codegen/apis/static/$version/data_$version.oas.yaml" +data_oas="codegen/apis/_build/$version/data_$version.oas.yaml" data_config="codegen/openapi-config.data.json" verify_spec_file_exists $data_oas generate_client $data_oas $data_config @@ -74,22 +87,12 @@ rm -rf pinecone/core/data cp -r build/pinecone/core/data pinecone/core/data # Generate control plane client -control_oas="codegen/apis/static/$version/control_$version.oas.yaml" +control_oas="codegen/apis/_build/$version/control_$version.oas.yaml" control_config="codegen/openapi-config.control.json" verify_spec_file_exists $control_oas generate_client $control_oas $control_config rm -rf pinecone/core/control cp -r build/pinecone/core/control pinecone/core/control - -# # 1. Concat data and control models/__init__.py files -# cat pinecone/core/client/models/__init__.py >> build/pinecone/core/client/models/__init__.py -# # 2. Copy control models files and combined __init__ file into pinecone -# cp -r build/pinecone/core/client/models/* pinecone/core/client/models -# # 3. Concat data and control apis/__init__.py files -# cat pinecone/core/client/apis/__init__.py >> build/pinecone/core/client/apis/__init__.py -# # 4. Copy control apis files and combined __init__ file into pinecone -# cp -r build/pinecone/core/client/apis/* pinecone/core/client/apis - # Format generated files poetry run black pinecone/core diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 499e5307d..e997a74a1 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -14,7 +14,7 @@ from .data import * from .models import * -from .core.client.models import ( +from .core.control.client.models import ( IndexModel, ) diff --git a/pinecone/config/config.py b/pinecone/config/config.py index df1c4e4f2..da906a6b3 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -1,9 +1,11 @@ from typing import NamedTuple, Optional, Dict import os -from pinecone.exceptions import PineconeConfigurationError +from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config.openapi import OpenApiConfigFactory -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.configuration import ( + Configuration as OpenApiConfiguration, +) from pinecone.utils import normalize_host from pinecone.utils.constants import SOURCE_TAG @@ -57,15 +59,28 @@ def build( 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) + 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 + 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 + 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) diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index 1ff4b7f53..4e56b2908 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -7,7 +7,9 @@ from urllib3.connection import HTTPConnection -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.configuration import ( + Configuration as OpenApiConfiguration, +) TCP_KEEPINTVL = 60 # Sec TCP_KEEPIDLE = 300 # Sec @@ -84,7 +86,13 @@ def _get_socket_options( 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_KEEPINTVL, + keep_alive_interval_sec, + ) + ] socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, keep_alive_tries)] # TCP Keep Alive Probes for Windows OS diff --git a/pinecone/config/pinecone_config.py b/pinecone/config/pinecone_config.py index 2960bb9e9..c447b2228 100644 --- a/pinecone/config/pinecone_config.py +++ b/pinecone/config/pinecone_config.py @@ -26,4 +26,9 @@ def build( 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) + return ConfigBuilder.build( + api_key=api_key, + host=host, + additional_headers=additional_headers, + **kwargs, + ) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index 89763066c..ffde835b9 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,7 +1,9 @@ from typing import Dict from pinecone.config import Config -from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi as IndexOperationsApi -from pinecone.core.client.exceptions import PineconeException +from pinecone.core.control.client.api.manage_indexes_api import ( + ManageIndexesApi as IndexOperationsApi, +) +from pinecone.core.control.client.exceptions import PineconeException from pinecone.utils import normalize_host diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index f46353761..89f01f528 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -1,22 +1,32 @@ import time import warnings import logging -from typing import Optional, Dict, Any, Union, List, cast, NamedTuple +from typing import Optional, Dict, Any, Union, List, Tuple, cast, NamedTuple from .index_host_store import IndexHostStore from pinecone.config import PineconeConfig, Config, ConfigBuilder -from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.client.api_client import ApiClient +from pinecone.core.control.client.api.manage_indexes_api import ( + ManageIndexesApi, +) +from pinecone.core.control.client.api_client import ApiClient -from pinecone.utils import normalize_host, setup_openapi_client, build_plugin_setup_client -from pinecone.core.client.models import ( +from pinecone.utils import ( + normalize_host, + setup_openapi_client, + build_plugin_setup_client, +) +from pinecone.core.control.client.models import ( CreateCollectionRequest, CreateIndexRequest, ConfigureIndexRequest, ConfigureIndexRequestSpec, ConfigureIndexRequestSpecPod, + IndexSpec, + ServerlessSpec as ServerlessSpecModel, + PodSpec as PodSpecModel, + PodSpecMetadataConfig, ) from pinecone.models import ServerlessSpec, PodSpec, IndexList, CollectionList from .langchain_import_warnings import _build_langchain_attribute_error_message @@ -233,7 +243,9 @@ def load_plugins(self): # try block just in case to make sure a bad plugin doesn't # halt client initialization. openapi_client_builder = build_plugin_setup_client( - config=self.config, openapi_config=self.openapi_config, pool_threads=self.pool_threads + config=self.config, + openapi_config=self.openapi_config, + pool_threads=self.pool_threads, ) install_plugins(self, openapi_client_builder) except Exception as e: @@ -305,25 +317,54 @@ def create_index( api_instance = self.index_api + def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: + return {arg_name: val for arg_name, val in args if val is not None} + if isinstance(spec, dict): - api_instance.create_index( - create_index_request=CreateIndexRequest(name=name, dimension=dimension, metric=metric, spec=spec) - ) + if "serverless" in spec: + index_spec = IndexSpec(serverless=ServerlessSpecModel(**spec["serverless"])) + elif "pod" in spec: + index_spec = IndexSpec(pod=PodSpecModel(**spec["pod"])) + else: + raise ValueError("spec must contain either 'serverless' or 'pod' key") elif isinstance(spec, ServerlessSpec): - api_instance.create_index( - create_index_request=CreateIndexRequest( - name=name, dimension=dimension, metric=metric, spec=spec.asdict() + index_spec = IndexSpec( + serverless=ServerlessSpecModel( + cloud=spec.cloud, + region=spec.region, ) ) elif isinstance(spec, PodSpec): - api_instance.create_index( - create_index_request=CreateIndexRequest( - name=name, dimension=dimension, metric=metric, spec=spec.asdict() + 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") + api_instance.create_index( + create_index_request=CreateIndexRequest( + name=name, + dimension=dimension, + metric=metric, + spec=index_spec, + ), + ) + def is_ready(): status = self._get_status(name) ready = status["ready"] @@ -477,7 +518,12 @@ def describe_index(self, name: str): return description - def configure_index(self, name: str, replicas: Optional[int] = None, pod_type: Optional[str] = None): + def configure_index( + self, + name: str, + replicas: Optional[int] = None, + pod_type: Optional[str] = None, + ): """This method is used to scale configuration fields for your pod-based Pinecone index. :param: name: the name of the Index diff --git a/pinecone/core/control/client/__init__.py b/pinecone/core/control/client/__init__.py index 88a122a68..1f0f51445 100644 --- a/pinecone/core/control/client/__init__.py +++ b/pinecone/core/control/client/__init__.py @@ -5,7 +5,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/api/__init__.py b/pinecone/core/control/client/api/__init__.py index 151eddb0d..a4a23bd49 100644 --- a/pinecone/core/control/client/api/__init__.py +++ b/pinecone/core/control/client/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.control.client.apis import ManageIndexesApi +# from pinecone.core.control.client.apis import InferenceApi diff --git a/pinecone/core/control/client/api/inference_api.py b/pinecone/core/control/client/api/inference_api.py new file mode 100644 index 000000000..ac9564c16 --- /dev/null +++ b/pinecone/core/control/client/api/inference_api.py @@ -0,0 +1,121 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.control.client.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types, +) +from pinecone.core.control.client.model.embed_request import EmbedRequest +from pinecone.core.control.client.model.embeddings_list import EmbeddingsList +from pinecone.core.control.client.model.inline_response401 import InlineResponse401 + + +class InferenceApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __embed(self, **kwargs): + """Embed data # noqa: E501 + + Generate embeddings for input 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.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. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + EmbeddingsList + If the method is called asynchronously, returns the request + thread. + """ + kwargs["async_req"] = kwargs.get("async_req", False) + kwargs["_return_http_data_only"] = kwargs.get("_return_http_data_only", True) + kwargs["_preload_content"] = kwargs.get("_preload_content", True) + kwargs["_request_timeout"] = kwargs.get("_request_timeout", None) + kwargs["_check_input_type"] = kwargs.get("_check_input_type", True) + kwargs["_check_return_type"] = kwargs.get("_check_return_type", True) + kwargs["_host_index"] = kwargs.get("_host_index") + return self.call_with_http_info(**kwargs) + + self.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, + ) diff --git a/pinecone/core/control/client/api/manage_indexes_api.py b/pinecone/core/control/client/api/manage_indexes_api.py index bf553b01f..43d7eb356 100644 --- a/pinecone/core/control/client/api/manage_indexes_api.py +++ b/pinecone/core/control/client/api/manage_indexes_api.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -26,9 +26,9 @@ from pinecone.core.control.client.model.configure_index_request import ConfigureIndexRequest from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest from pinecone.core.control.client.model.create_index_request import CreateIndexRequest -from pinecone.core.control.client.model.error_response import ErrorResponse from pinecone.core.control.client.model.index_list import IndexList from pinecone.core.control.client.model.index_model import IndexModel +from pinecone.core.control.client.model.inline_response401 import InlineResponse401 class ManageIndexesApi(object): @@ -101,12 +101,7 @@ def __configure_index(self, index_name, configure_index_request, **kwargs): "endpoint_path": "/indexes/{index_name}", "operation_id": "configure_index", "http_method": "PATCH", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -145,7 +140,7 @@ def __configure_index(self, index_name, configure_index_request, **kwargs): 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 + 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 @@ -198,12 +193,7 @@ def __create_collection(self, create_collection_request, **kwargs): "endpoint_path": "/collections", "operation_id": "create_collection", "http_method": "POST", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -236,7 +226,7 @@ def __create_collection(self, create_collection_request, **kwargs): 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 + 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 @@ -289,12 +279,7 @@ def __create_index(self, create_index_request, **kwargs): "endpoint_path": "/indexes", "operation_id": "create_index", "http_method": "POST", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -327,7 +312,7 @@ def __create_index(self, create_index_request, **kwargs): 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 + 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 @@ -380,12 +365,7 @@ def __delete_collection(self, collection_name, **kwargs): "endpoint_path": "/collections/{collection_name}", "operation_id": "delete_collection", "http_method": "DELETE", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -476,12 +456,7 @@ def __delete_index(self, index_name, **kwargs): "endpoint_path": "/indexes/{index_name}", "operation_id": "delete_index", "http_method": "DELETE", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -519,7 +494,7 @@ def __delete_index(self, index_name, **kwargs): 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 + 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 @@ -572,12 +547,7 @@ def __describe_collection(self, collection_name, **kwargs): "endpoint_path": "/collections/{collection_name}", "operation_id": "describe_collection", "http_method": "GET", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -668,12 +638,7 @@ def __describe_index(self, index_name, **kwargs): "endpoint_path": "/indexes/{index_name}", "operation_id": "describe_index", "http_method": "GET", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={ "all": [ @@ -711,7 +676,7 @@ def __describe_index(self, index_name, **kwargs): 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 + 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 @@ -761,12 +726,7 @@ def __list_collections(self, **kwargs): "endpoint_path": "/collections", "operation_id": "list_collections", "http_method": "GET", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={"all": [], "required": [], "nullable": [], "enum": [], "validation": []}, root_map={ @@ -838,12 +798,7 @@ def __list_indexes(self, **kwargs): "endpoint_path": "/indexes", "operation_id": "list_indexes", "http_method": "GET", - "servers": [ - { - "url": "https://api.pinecone.io", - "description": "No description provided", - }, - ], + "servers": None, }, params_map={"all": [], "required": [], "nullable": [], "enum": [], "validation": []}, root_map={ diff --git a/pinecone/core/control/client/api_client.py b/pinecone/core/control/client/api_client.py index c36b00c7e..6f9032adf 100644 --- a/pinecone/core/control/client/api_client.py +++ b/pinecone/core/control/client/api_client.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -761,11 +761,11 @@ def __call__(self, *args, **kwargs): """This method is invoked when endpoints are called Example: - api_instance = ManageIndexesApi() - api_instance.configure_index # this is an instance of the class Endpoint - api_instance.configure_index() # this invokes api_instance.configure_index.__call__() + 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.configure_index.callable or self.callable in this class + api_instance.embed.callable or self.callable in this class """ return self.callable(self, *args, **kwargs) diff --git a/pinecone/core/control/client/apis/__init__.py b/pinecone/core/control/client/apis/__init__.py index 55a7599b7..d0d2a0a9f 100644 --- a/pinecone/core/control/client/apis/__init__.py +++ b/pinecone/core/control/client/apis/__init__.py @@ -5,7 +5,7 @@ # raise a `RecursionError`. # In order to avoid this, import only the API that you directly need like: # -# from .api.manage_indexes_api import ManageIndexesApi +# from .api.inference_api import InferenceApi # # or import this package, but before doing it, use: # @@ -13,4 +13,5 @@ # sys.setrecursionlimit(n) # Import APIs into API package: +from pinecone.core.control.client.api.inference_api import InferenceApi from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi diff --git a/pinecone/core/control/client/configuration.py b/pinecone/core/control/client/configuration.py index c25bb2319..f5b01dcd4 100644 --- a/pinecone/core/control/client/configuration.py +++ b/pinecone/core/control/client/configuration.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -416,7 +416,7 @@ def to_debug_report(self): "Python SDK Debug Report:\n" "OS: {env}\n" "Python Version: {pyversion}\n" - "Version of the API: 2024-04\n" + "Version of the API: 2024-07\n" "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) ) diff --git a/pinecone/core/control/client/exceptions.py b/pinecone/core/control/client/exceptions.py index aac96ceaa..ede69833a 100644 --- a/pinecone/core/control/client/exceptions.py +++ b/pinecone/core/control/client/exceptions.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/collection_list.py b/pinecone/core/control/client/model/collection_list.py index b691b88e5..151307897 100644 --- a/pinecone/core/control/client/model/collection_list.py +++ b/pinecone/core/control/client/model/collection_list.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/collection_model.py b/pinecone/core/control/client/model/collection_model.py index 968f8fdea..4689ce326 100644 --- a/pinecone/core/control/client/model/collection_model.py +++ b/pinecone/core/control/client/model/collection_model.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/configure_index_request.py b/pinecone/core/control/client/model/configure_index_request.py index ee3ff0678..8917f9f56 100644 --- a/pinecone/core/control/client/model/configure_index_request.py +++ b/pinecone/core/control/client/model/configure_index_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/configure_index_request_spec.py b/pinecone/core/control/client/model/configure_index_request_spec.py index e5df7e80c..a3d4f7fc3 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec.py +++ b/pinecone/core/control/client/model/configure_index_request_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/configure_index_request_spec_pod.py b/pinecone/core/control/client/model/configure_index_request_spec_pod.py index 2f1d46239..5aa5c3d7b 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/control/client/model/configure_index_request_spec_pod.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -29,12 +29,6 @@ from pinecone.core.control.client.exceptions import PineconeApiAttributeError -def lazy_import(): - from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas - - globals()["PodSpecReplicas"] = PodSpecReplicas - - class ConfigureIndexRequestSpecPod(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -61,7 +55,11 @@ class ConfigureIndexRequestSpecPod(ModelNormal): allowed_values = {} - validations = {} + validations = { + ("replicas",): { + "inclusive_minimum": 1, + }, + } @cached_property def additional_properties_type(): @@ -69,7 +67,6 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ - lazy_import() return ( bool, date, @@ -94,9 +91,8 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ - lazy_import() return { - "replicas": (PodSpecReplicas,), # noqa: E501 + "replicas": (int,), # noqa: E501 "pod_type": (str,), # noqa: E501 } @@ -149,7 +145,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (PodSpecReplicas): [optional] # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 """ @@ -237,7 +233,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (PodSpecReplicas): [optional] # noqa: E501 + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. [optional] if omitted the server will use the default value of "p1.x1" # noqa: E501 """ diff --git a/pinecone/core/control/client/model/create_collection_request.py b/pinecone/core/control/client/model/create_collection_request.py index c9e1af7e7..e48210f54 100644 --- a/pinecone/core/control/client/model/create_collection_request.py +++ b/pinecone/core/control/client/model/create_collection_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/create_index_request.py b/pinecone/core/control/client/model/create_index_request.py index dcd5c8d94..c229af885 100644 --- a/pinecone/core/control/client/model/create_index_request.py +++ b/pinecone/core/control/client/model/create_index_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -30,13 +30,9 @@ def lazy_import(): - from pinecone.core.control.client.model.index_dimension import IndexDimension - from pinecone.core.control.client.model.index_metric import IndexMetric - from pinecone.core.control.client.model.index_name import IndexName + from pinecone.core.control.client.model.index_spec import IndexSpec - globals()["IndexDimension"] = IndexDimension - globals()["IndexMetric"] = IndexMetric - globals()["IndexName"] = IndexName + globals()["IndexSpec"] = IndexSpec class CreateIndexRequest(ModelNormal): @@ -63,9 +59,24 @@ class CreateIndexRequest(ModelNormal): as additional properties values. """ - allowed_values = {} + allowed_values = { + ("metric",): { + "COSINE": "cosine", + "EUCLIDEAN": "euclidean", + "DOTPRODUCT": "dotproduct", + }, + } - validations = {} + validations = { + ("name",): { + "max_length": 45, + "min_length": 1, + }, + ("dimension",): { + "inclusive_maximum": 20000, + "inclusive_minimum": 1, + }, + } @cached_property def additional_properties_type(): @@ -100,10 +111,10 @@ def openapi_types(): """ lazy_import() return { - "name": (IndexName,), # noqa: E501 - "dimension": (IndexDimension,), # noqa: E501 - "spec": (dict,), # noqa: E501 - "metric": (IndexMetric,), # noqa: E501 + "name": (str,), # noqa: E501 + "dimension": (int,), # noqa: E501 + "spec": (IndexSpec,), # noqa: E501 + "metric": (str,), # noqa: E501 } @cached_property @@ -127,9 +138,9 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 """CreateIndexRequest - a model defined in OpenAPI Args: - name (IndexName): - dimension (IndexDimension): - spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + dimension (int): The dimensions of the vectors to be inserted in the index. + spec (IndexSpec): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -162,7 +173,7 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - metric (IndexMetric): [optional] # noqa: E501 + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -222,9 +233,9 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 """CreateIndexRequest - a model defined in OpenAPI Args: - name (IndexName): - dimension (IndexDimension): - spec (dict): The spec object defines how the index should be deployed. For serverless indexes, you define only the cloud and region where the index should be hosted. For pod-based indexes, you define the environment where the index should be hosted, the pod type and size to use, and other index characteristics. + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + dimension (int): The dimensions of the vectors to be inserted in the index. + spec (IndexSpec): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -257,7 +268,7 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - metric (IndexMetric): [optional] # noqa: E501 + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/control/client/model/index_dimension.py b/pinecone/core/control/client/model/embed_request.py similarity index 76% rename from pinecone/core/control/client/model/index_dimension.py rename to pinecone/core/control/client/model/embed_request.py index b330b041c..5c26b145d 100644 --- a/pinecone/core/control/client/model/index_dimension.py +++ b/pinecone/core/control/client/model/embed_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -29,7 +29,15 @@ from pinecone.core.control.client.exceptions import PineconeApiAttributeError -class IndexDimension(ModelSimple): +def lazy_import(): + from pinecone.core.control.client.model.embed_request_inputs import EmbedRequestInputs + from pinecone.core.control.client.model.embed_request_parameters import EmbedRequestParameters + + globals()["EmbedRequestInputs"] = EmbedRequestInputs + globals()["EmbedRequestParameters"] = EmbedRequestParameters + + +class EmbedRequest(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -40,6 +48,10 @@ class IndexDimension(ModelSimple): 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, @@ -51,12 +63,7 @@ class IndexDimension(ModelSimple): allowed_values = {} - validations = { - ("value",): { - "inclusive_maximum": 20000, - "inclusive_minimum": 1, - }, - } + validations = {} @cached_property def additional_properties_type(): @@ -64,6 +71,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ + lazy_import() return ( bool, date, @@ -88,42 +96,37 @@ def openapi_types(): openapi_types (dict): The key is attribute name and the value is attribute type. """ + lazy_import() return { - "value": (int,), + "model": (str,), # noqa: E501 + "inputs": ([EmbedRequestInputs],), # noqa: E501 + "parameters": (EmbedRequestParameters,), # noqa: E501 } @cached_property def discriminator(): return None - attribute_map = {} + attribute_map = { + "model": "model", # noqa: E501 + "inputs": "inputs", # noqa: E501 + "parameters": "parameters", # noqa: E501 + } - read_only_vars = set() + read_only_vars = {} - _composed_schemas = None - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) + _composed_schemas = {} + @classmethod @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IndexDimension - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. + def _from_openapi_data(cls, model, inputs, *args, **kwargs): # noqa: E501 + """EmbedRequest - a model defined in OpenAPI Args: - args[0] (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + model (str): + inputs ([EmbedRequestInputs]): Keyword Args: - value (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -154,27 +157,17 @@ def __init__(self, *args, **kwargs): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + parameters (EmbedRequestParameters): [optional] # noqa: E501 """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _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." @@ -192,30 +185,41 @@ def __init__(self, *args, **kwargs): self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IndexDimension - a model defined in OpenAPI + 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 - Note that value can be passed either in args or in kwargs, but not in both. + 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): # noqa: E501 + """EmbedRequest - a model defined in OpenAPI Args: - args[0] (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 + model (str): + inputs ([EmbedRequestInputs]): Keyword Args: - value (int): The dimensions of the vectors to be inserted in the index.. # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -246,26 +250,12 @@ def _from_openapi_data(cls, *args, **kwargs): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + parameters (EmbedRequestParameters): [optional] # noqa: E501 """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) @@ -286,16 +276,21 @@ def _from_openapi_data(cls, *args, **kwargs): 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 + 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/control/client/model/pod_spec_shards.py b/pinecone/core/control/client/model/embed_request_inputs.py similarity index 78% rename from pinecone/core/control/client/model/pod_spec_shards.py rename to pinecone/core/control/client/model/embed_request_inputs.py index 18ffa9a14..f3cf16c22 100644 --- a/pinecone/core/control/client/model/pod_spec_shards.py +++ b/pinecone/core/control/client/model/embed_request_inputs.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -29,7 +29,7 @@ from pinecone.core.control.client.exceptions import PineconeApiAttributeError -class PodSpecShards(ModelSimple): +class EmbedRequestInputs(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -40,6 +40,10 @@ class PodSpecShards(ModelSimple): 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, @@ -51,11 +55,7 @@ class PodSpecShards(ModelSimple): allowed_values = {} - validations = { - ("value",): { - "inclusive_minimum": 1, - }, - } + validations = {} @cached_property def additional_properties_type(): @@ -88,41 +88,27 @@ def openapi_types(): and the value is attribute type. """ return { - "value": (int,), + "text": (str,), # noqa: E501 } @cached_property def discriminator(): return None - attribute_map = {} - - read_only_vars = set() + attribute_map = { + "text": "text", # noqa: E501 + } - _composed_schemas = None + read_only_vars = {} - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) + _composed_schemas = {} + @classmethod @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """PodSpecShards - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EmbedRequestInputs - a model defined in OpenAPI Keyword Args: - value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -153,23 +139,17 @@ def __init__(self, *args, **kwargs): 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 """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = 1 _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) _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." @@ -187,30 +167,35 @@ def __init__(self, *args, **kwargs): self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """PodSpecShards - a model defined in OpenAPI + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is 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 - Note that value can be passed either in args or in kwargs, but not in both. + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) - Args: - args[0] (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EmbedRequestInputs - a model defined in OpenAPI Keyword Args: - value (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. if omitted defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -241,22 +226,12 @@ def _from_openapi_data(cls, *args, **kwargs): 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 """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = 1 _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) @@ -277,16 +252,19 @@ def _from_openapi_data(cls, *args, **kwargs): 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 + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is 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/control/client/model/embed_request_parameters.py b/pinecone/core/control/client/model/embed_request_parameters.py new file mode 100644 index 000000000..fa32e1477 --- /dev/null +++ b/pinecone/core/control/client/model/embed_request_parameters.py @@ -0,0 +1,274 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class EmbedRequestParameters(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "input_type": (str,), # noqa: E501 + "truncate": (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "input_type": "input_type", # noqa: E501 + "truncate": "truncate", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EmbedRequestParameters - 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,) + input_type (str): Common property used to distinguish between types of data.. [optional] # noqa: E501 + truncate (str): How to handle inputs longer than those supported by the model. If NONE, when the input exceeds the maximum input token length an error will be returned.. [optional] if omitted the server will use the default value of "END" # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EmbedRequestParameters - 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,) + input_type (str): Common property used to distinguish between types of data.. [optional] # noqa: E501 + truncate (str): How to handle inputs longer than those supported by the model. If NONE, when the input exceeds the maximum input token length an error will be returned.. [optional] if omitted the server will use the default value of "END" # 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/control/client/model/embedding.py b/pinecone/core/control/client/model/embedding.py new file mode 100644 index 000000000..8fe54a75f --- /dev/null +++ b/pinecone/core/control/client/model/embedding.py @@ -0,0 +1,270 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class Embedding(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "values": ([float],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "values": "values", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Embedding - 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 ([float]): The embedding values.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Embedding - 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 ([float]): The embedding values.. [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/control/client/model/embeddings_list.py b/pinecone/core/control/client/model/embeddings_list.py new file mode 100644 index 000000000..3098052c2 --- /dev/null +++ b/pinecone/core/control/client/model/embeddings_list.py @@ -0,0 +1,288 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.control.client.model.embedding import Embedding + from pinecone.core.control.client.model.embeddings_list_usage import EmbeddingsListUsage + + globals()["Embedding"] = Embedding + globals()["EmbeddingsListUsage"] = EmbeddingsListUsage + + +class EmbeddingsList(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + "model": (str,), # noqa: E501 + "data": ([Embedding],), # noqa: E501 + "usage": (EmbeddingsListUsage,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "model": "model", # noqa: E501 + "data": "data", # noqa: E501 + "usage": "usage", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EmbeddingsList - 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): [optional] # noqa: E501 + data ([Embedding]): [optional] # noqa: E501 + usage (EmbeddingsListUsage): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EmbeddingsList - 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): [optional] # noqa: E501 + data ([Embedding]): [optional] # noqa: E501 + usage (EmbeddingsListUsage): [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/control/client/model/embeddings_list_usage.py b/pinecone/core/control/client/model/embeddings_list_usage.py new file mode 100644 index 000000000..0bfe41c86 --- /dev/null +++ b/pinecone/core/control/client/model/embeddings_list_usage.py @@ -0,0 +1,270 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +class EmbeddingsListUsage(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "total_tokens": (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "total_tokens": "total_tokens", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # 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): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _path_to_item = kwargs.pop("_path_to_item", ()) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if ( + var_name not in self.attribute_map + and self._configuration is not None + and self._configuration.discard_unknown_keys + and self.additional_properties_type is None + ): + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """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): [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/control/client/model/index_list.py b/pinecone/core/control/client/model/index_list.py index 80f09b786..2aeea1d46 100644 --- a/pinecone/core/control/client/model/index_list.py +++ b/pinecone/core/control/client/model/index_list.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/index_metric.py b/pinecone/core/control/client/model/index_metric.py deleted file mode 100644 index 80ca7c26d..000000000 --- a/pinecone/core/control/client/model/index_metric.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 - - The version of the OpenAPI document: 2024-04 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.control.client.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError - - -class IndexMetric(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - ("value",): { - "COSINE": "cosine", - "EUCLIDEAN": "euclidean", - "DOTPRODUCT": "dotproduct", - }, - } - - validations = {} - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "value": (str,), - } - - @cached_property - def discriminator(): - return None - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IndexMetric - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - - Keyword Args: - value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = "cosine" - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IndexMetric - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - - Keyword Args: - value (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. if omitted defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = "cosine" - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/control/client/model/index_model.py b/pinecone/core/control/client/model/index_model.py index ddd669254..cb6b64ece 100644 --- a/pinecone/core/control/client/model/index_model.py +++ b/pinecone/core/control/client/model/index_model.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -30,17 +30,11 @@ def lazy_import(): - from pinecone.core.control.client.model.index_dimension import IndexDimension - from pinecone.core.control.client.model.index_metric import IndexMetric from pinecone.core.control.client.model.index_model_spec import IndexModelSpec from pinecone.core.control.client.model.index_model_status import IndexModelStatus - from pinecone.core.control.client.model.index_name import IndexName - globals()["IndexDimension"] = IndexDimension - globals()["IndexMetric"] = IndexMetric globals()["IndexModelSpec"] = IndexModelSpec globals()["IndexModelStatus"] = IndexModelStatus - globals()["IndexName"] = IndexName class IndexModel(ModelNormal): @@ -67,9 +61,24 @@ class IndexModel(ModelNormal): as additional properties values. """ - allowed_values = {} + allowed_values = { + ("metric",): { + "COSINE": "cosine", + "EUCLIDEAN": "euclidean", + "DOTPRODUCT": "dotproduct", + }, + } - validations = {} + validations = { + ("name",): { + "max_length": 45, + "min_length": 1, + }, + ("dimension",): { + "inclusive_maximum": 20000, + "inclusive_minimum": 1, + }, + } @cached_property def additional_properties_type(): @@ -104,9 +113,9 @@ def openapi_types(): """ lazy_import() return { - "name": (IndexName,), # noqa: E501 - "dimension": (IndexDimension,), # noqa: E501 - "metric": (IndexMetric,), # noqa: E501 + "name": (str,), # noqa: E501 + "dimension": (int,), # noqa: E501 + "metric": (str,), # noqa: E501 "host": (str,), # noqa: E501 "spec": (IndexModelSpec,), # noqa: E501 "status": (IndexModelStatus,), # noqa: E501 @@ -131,18 +140,18 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: - name (IndexName): - dimension (IndexDimension): - metric (IndexMetric): + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + dimension (int): The dimensions of the vectors to be inserted in the index. host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -175,6 +184,7 @@ def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, _visited_composed_classes = (Animal,) """ + metric = kwargs.get("metric", "cosine") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) @@ -231,18 +241,18 @@ def _from_openapi_data(cls, name, dimension, metric, host, spec, status, *args, ) @convert_js_args_to_python_args - def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs): # noqa: E501 + def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noqa: E501 """IndexModel - a model defined in OpenAPI Args: - name (IndexName): - dimension (IndexDimension): - metric (IndexMetric): + name (str): The name of the index. Resource name must be 1-45 characters long, start and end with an alphanumeric character, and consist only of lower case alphanumeric characters or '-'. + dimension (int): The dimensions of the vectors to be inserted in the index. host (str): The URL address where the index is hosted. spec (IndexModelSpec): status (IndexModelStatus): Keyword Args: + metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. defaults to "cosine", must be one of ["cosine", "euclidean", "dotproduct", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -275,6 +285,7 @@ def __init__(self, name, dimension, metric, host, spec, status, *args, **kwargs) _visited_composed_classes = (Animal,) """ + metric = kwargs.get("metric", "cosine") _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) diff --git a/pinecone/core/control/client/model/index_model_spec.py b/pinecone/core/control/client/model/index_model_spec.py index 078000b19..5dd42f89c 100644 --- a/pinecone/core/control/client/model/index_model_spec.py +++ b/pinecone/core/control/client/model/index_model_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/index_model_status.py b/pinecone/core/control/client/model/index_model_status.py index b5417354a..062c653b7 100644 --- a/pinecone/core/control/client/model/index_model_status.py +++ b/pinecone/core/control/client/model/index_model_status.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/index_name.py b/pinecone/core/control/client/model/index_name.py deleted file mode 100644 index eb94ddd24..000000000 --- a/pinecone/core/control/client/model/index_name.py +++ /dev/null @@ -1,301 +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 - - The version of the OpenAPI document: 2024-04 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.control.client.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError - - -class IndexName(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = {} - - validations = { - ("value",): { - "max_length": 45, - "min_length": 1, - }, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "value": (str,), - } - - @cached_property - def discriminator(): - return None - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IndexName - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The 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 '-'. . # noqa: E501 - - Keyword Args: - value (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 '-'. . # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IndexName - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): The 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 '-'. . # noqa: E501 - - Keyword Args: - value (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 '-'. . # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - raise PineconeApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/control/client/model/index_spec.py b/pinecone/core/control/client/model/index_spec.py new file mode 100644 index 000000000..8c93880a2 --- /dev/null +++ b/pinecone/core/control/client/model/index_spec.py @@ -0,0 +1,267 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.control.client.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from pinecone.core.control.client.exceptions import PineconeApiAttributeError + + +def lazy_import(): + from pinecone.core.control.client.model.pod_spec import PodSpec + from pinecone.core.control.client.model.serverless_spec import ServerlessSpec + + globals()["PodSpec"] = PodSpec + globals()["ServerlessSpec"] = ServerlessSpec + + +class IndexSpec(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = {} + + validations = {} + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + "serverless": (ServerlessSpec,), # noqa: E501 + "pod": (PodSpec,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + attribute_map = { + "serverless": "serverless", # noqa: E501 + "pod": "pod", # noqa: E501 + } + + read_only_vars = {} + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # 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): # 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/control/client/model/error_response.py b/pinecone/core/control/client/model/inline_response401.py similarity index 95% rename from pinecone/core/control/client/model/error_response.py rename to pinecone/core/control/client/model/inline_response401.py index d0ca5ce6a..dd7dd9467 100644 --- a/pinecone/core/control/client/model/error_response.py +++ b/pinecone/core/control/client/model/inline_response401.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -30,12 +30,12 @@ def lazy_import(): - from pinecone.core.control.client.model.error_response_error import ErrorResponseError + from pinecone.core.control.client.model.inline_response401_error import InlineResponse401Error - globals()["ErrorResponseError"] = ErrorResponseError + globals()["InlineResponse401Error"] = InlineResponse401Error -class ErrorResponse(ModelNormal): +class InlineResponse401(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -97,7 +97,7 @@ def openapi_types(): lazy_import() return { "status": (int,), # noqa: E501 - "error": (ErrorResponseError,), # noqa: E501 + "error": (InlineResponse401Error,), # noqa: E501 } @cached_property @@ -116,11 +116,11 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 - """ErrorResponse - a model defined in OpenAPI + """InlineResponse401 - a model defined in OpenAPI Args: status (int): The HTTP status code of the error. - error (ErrorResponseError): + error (InlineResponse401Error): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -208,11 +208,11 @@ def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, status, error, *args, **kwargs): # noqa: E501 - """ErrorResponse - a model defined in OpenAPI + """InlineResponse401 - a model defined in OpenAPI Args: status (int): The HTTP status code of the error. - error (ErrorResponseError): + error (InlineResponse401Error): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/control/client/model/error_response_error.py b/pinecone/core/control/client/model/inline_response401_error.py similarity index 98% rename from pinecone/core/control/client/model/error_response_error.py rename to pinecone/core/control/client/model/inline_response401_error.py index 1828b047c..4328e3374 100644 --- a/pinecone/core/control/client/model/error_response_error.py +++ b/pinecone/core/control/client/model/inline_response401_error.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -29,7 +29,7 @@ from pinecone.core.control.client.exceptions import PineconeApiAttributeError -class ErrorResponseError(ModelNormal): +class InlineResponse401Error(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -131,7 +131,7 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 - """ErrorResponseError - a model defined in OpenAPI + """InlineResponse401Error - a model defined in OpenAPI Args: code (str): @@ -224,7 +224,7 @@ def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, code, message, *args, **kwargs): # noqa: E501 - """ErrorResponseError - a model defined in OpenAPI + """InlineResponse401Error - a model defined in OpenAPI Args: code (str): diff --git a/pinecone/core/control/client/model/pod_spec.py b/pinecone/core/control/client/model/pod_spec.py index 7510057b7..0a995cada 100644 --- a/pinecone/core/control/client/model/pod_spec.py +++ b/pinecone/core/control/client/model/pod_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -31,12 +31,8 @@ def lazy_import(): from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig - from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas - from pinecone.core.control.client.model.pod_spec_shards import PodSpecShards globals()["PodSpecMetadataConfig"] = PodSpecMetadataConfig - globals()["PodSpecReplicas"] = PodSpecReplicas - globals()["PodSpecShards"] = PodSpecShards class PodSpec(ModelNormal): @@ -69,6 +65,12 @@ class PodSpec(ModelNormal): ("pods",): { "inclusive_minimum": 1, }, + ("replicas",): { + "inclusive_minimum": 1, + }, + ("shards",): { + "inclusive_minimum": 1, + }, } @cached_property @@ -105,10 +107,10 @@ def openapi_types(): lazy_import() return { "environment": (str,), # noqa: E501 - "replicas": (PodSpecReplicas,), # noqa: E501 - "shards": (PodSpecShards,), # noqa: E501 "pod_type": (str,), # noqa: E501 "pods": (int,), # noqa: E501 + "replicas": (int,), # noqa: E501 + "shards": (int,), # noqa: E501 "metadata_config": (PodSpecMetadataConfig,), # noqa: E501 "source_collection": (str,), # noqa: E501 } @@ -119,10 +121,10 @@ def discriminator(): attribute_map = { "environment": "environment", # noqa: E501 - "replicas": "replicas", # noqa: E501 - "shards": "shards", # noqa: E501 "pod_type": "pod_type", # noqa: E501 "pods": "pods", # noqa: E501 + "replicas": "replicas", # noqa: E501 + "shards": "shards", # noqa: E501 "metadata_config": "metadata_config", # noqa: E501 "source_collection": "source_collection", # noqa: E501 } @@ -133,13 +135,11 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, environment, replicas, shards, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 """PodSpec - a model defined in OpenAPI Args: environment (str): The environment where the index is hosted. - replicas (PodSpecReplicas): - shards (PodSpecShards): 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 @@ -174,6 +174,8 @@ def _from_openapi_data(cls, environment, replicas, shards, *args, **kwargs): # Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ @@ -207,8 +209,6 @@ def _from_openapi_data(cls, environment, replicas, shards, *args, **kwargs): # self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment - self.replicas = replicas - self.shards = shards self.pod_type = pod_type self.pods = pods for var_name, var_value in kwargs.items(): @@ -235,13 +235,11 @@ def _from_openapi_data(cls, environment, replicas, shards, *args, **kwargs): # ) @convert_js_args_to_python_args - def __init__(self, environment, replicas, shards, *args, **kwargs): # noqa: E501 + def __init__(self, environment, *args, **kwargs): # noqa: E501 """PodSpec - a model defined in OpenAPI Args: environment (str): The environment where the index is hosted. - replicas (PodSpecReplicas): - shards (PodSpecShards): 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 @@ -276,6 +274,8 @@ def __init__(self, environment, replicas, shards, *args, **kwargs): # noqa: E50 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ @@ -307,8 +307,6 @@ def __init__(self, environment, replicas, shards, *args, **kwargs): # noqa: E50 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment - self.replicas = replicas - self.shards = shards self.pod_type = pod_type self.pods = pods for var_name, var_value in kwargs.items(): diff --git a/pinecone/core/control/client/model/pod_spec_metadata_config.py b/pinecone/core/control/client/model/pod_spec_metadata_config.py index 4847a2bae..69031c7df 100644 --- a/pinecone/core/control/client/model/pod_spec_metadata_config.py +++ b/pinecone/core/control/client/model/pod_spec_metadata_config.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model/pod_spec_replicas.py b/pinecone/core/control/client/model/pod_spec_replicas.py deleted file mode 100644 index 58aaee18e..000000000 --- a/pinecone/core/control/client/model/pod_spec_replicas.py +++ /dev/null @@ -1,292 +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 - - The version of the OpenAPI document: 2024-04 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 - -from pinecone.core.control.client.model_utils import ( # noqa: F401 - PineconeApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, -) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError - - -class PodSpecReplicas(ModelSimple): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = {} - - validations = { - ("value",): { - "inclusive_minimum": 1, - }, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return ( - bool, - date, - datetime, - dict, - float, - int, - list, - str, - none_type, - ) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - "value": (int,), - } - - @cached_property - def discriminator(): - return None - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set( - [ - "_data_store", - "_check_type", - "_spec_property_naming", - "_path_to_item", - "_configuration", - "_visited_composed_classes", - ] - ) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """PodSpecReplicas - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 - - Keyword Args: - value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = 1 - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """PodSpecReplicas - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 - - Keyword Args: - value (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. if omitted defaults to 1 # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop("_path_to_item", ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if "value" in kwargs: - value = kwargs.pop("value") - elif args: - args = list(args) - value = args.pop(0) - else: - value = 1 - - _check_type = kwargs.pop("_check_type", True) - _spec_property_naming = kwargs.pop("_spec_property_naming", False) - _configuration = kwargs.pop("_configuration", None) - _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) - - if args: - raise PineconeApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." - % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise PineconeApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." - % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self diff --git a/pinecone/core/control/client/model/serverless_spec.py b/pinecone/core/control/client/model/serverless_spec.py index 32bf9373b..7c675b4cb 100644 --- a/pinecone/core/control/client/model/serverless_spec.py +++ b/pinecone/core/control/client/model/serverless_spec.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/model_utils.py b/pinecone/core/control/client/model_utils.py index f0c9d2d70..c3d5b4115 100644 --- a/pinecone/core/control/client/model_utils.py +++ b/pinecone/core/control/client/model_utils.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/control/client/models/__init__.py b/pinecone/core/control/client/models/__init__.py index 2e225c956..a6400a47a 100644 --- a/pinecone/core/control/client/models/__init__.py +++ b/pinecone/core/control/client/models/__init__.py @@ -16,17 +16,19 @@ from pinecone.core.control.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest from pinecone.core.control.client.model.create_index_request import CreateIndexRequest -from pinecone.core.control.client.model.error_response import ErrorResponse -from pinecone.core.control.client.model.error_response_error import ErrorResponseError -from pinecone.core.control.client.model.index_dimension import IndexDimension +from pinecone.core.control.client.model.embed_request import EmbedRequest +from pinecone.core.control.client.model.embed_request_inputs import EmbedRequestInputs +from pinecone.core.control.client.model.embed_request_parameters import EmbedRequestParameters +from pinecone.core.control.client.model.embedding import Embedding +from pinecone.core.control.client.model.embeddings_list import EmbeddingsList +from pinecone.core.control.client.model.embeddings_list_usage import EmbeddingsListUsage from pinecone.core.control.client.model.index_list import IndexList -from pinecone.core.control.client.model.index_metric import IndexMetric from pinecone.core.control.client.model.index_model import IndexModel from pinecone.core.control.client.model.index_model_spec import IndexModelSpec from pinecone.core.control.client.model.index_model_status import IndexModelStatus -from pinecone.core.control.client.model.index_name import IndexName +from pinecone.core.control.client.model.index_spec import IndexSpec +from pinecone.core.control.client.model.inline_response401 import InlineResponse401 +from pinecone.core.control.client.model.inline_response401_error import InlineResponse401Error from pinecone.core.control.client.model.pod_spec import PodSpec from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig -from pinecone.core.control.client.model.pod_spec_replicas import PodSpecReplicas -from pinecone.core.control.client.model.pod_spec_shards import PodSpecShards from pinecone.core.control.client.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/control/client/rest.py b/pinecone/core/control/client/rest.py index fc58e24b9..191a32080 100644 --- a/pinecone/core/control/client/rest.py +++ b/pinecone/core/control/client/rest.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/__init__.py b/pinecone/core/data/client/__init__.py index e7904f3e0..1ed0378a5 100644 --- a/pinecone/core/data/client/__init__.py +++ b/pinecone/core/data/client/__init__.py @@ -5,7 +5,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/api/data_plane_api.py b/pinecone/core/data/client/api/data_plane_api.py index 26d91d709..26653ae5c 100644 --- a/pinecone/core/data/client/api/data_plane_api.py +++ b/pinecone/core/data/client/api/data_plane_api.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/api_client.py b/pinecone/core/data/client/api_client.py index 29e1c4f57..9d03d2729 100644 --- a/pinecone/core/data/client/api_client.py +++ b/pinecone/core/data/client/api_client.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/configuration.py b/pinecone/core/data/client/configuration.py index 01f36d2b6..de009c460 100644 --- a/pinecone/core/data/client/configuration.py +++ b/pinecone/core/data/client/configuration.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -416,7 +416,7 @@ def to_debug_report(self): "Python SDK Debug Report:\n" "OS: {env}\n" "Python Version: {pyversion}\n" - "Version of the API: 2024-04\n" + "Version of the API: 2024-07\n" "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) ) diff --git a/pinecone/core/data/client/exceptions.py b/pinecone/core/data/client/exceptions.py index 55f21fdc7..54cb943c5 100644 --- a/pinecone/core/data/client/exceptions.py +++ b/pinecone/core/data/client/exceptions.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/delete_request.py b/pinecone/core/data/client/model/delete_request.py index d31507df8..c6d4e5d94 100644 --- a/pinecone/core/data/client/model/delete_request.py +++ b/pinecone/core/data/client/model/delete_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -150,7 +150,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -240,7 +240,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 ids ([str]): Vectors to delete.. [optional] # noqa: E501 delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] if omitted the server will use the default value of False # noqa: E501 namespace (str): The namespace to delete vectors from, if applicable.. [optional] # noqa: E501 - filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 + filter ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See [Filter with metadata](https://docs.pinecone.io/guides/data/filter-with-metadata). Serverless indexes do not support delete by metadata. Instead, you can use the `list` operation to fetch the vector IDs based on their common ID prefix and then delete the records by ID.. [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/data/client/model/describe_index_stats_request.py b/pinecone/core/data/client/model/describe_index_stats_request.py index e56c01dc8..a383ef287 100644 --- a/pinecone/core/data/client/model/describe_index_stats_request.py +++ b/pinecone/core/data/client/model/describe_index_stats_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/describe_index_stats_response.py b/pinecone/core/data/client/model/describe_index_stats_response.py index 79db67494..7a643d882 100644 --- a/pinecone/core/data/client/model/describe_index_stats_response.py +++ b/pinecone/core/data/client/model/describe_index_stats_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ @@ -155,7 +155,7 @@ def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index). . [optional] # noqa: E501 total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 """ @@ -245,7 +245,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 _visited_composed_classes = (Animal,) namespaces ({str: (NamespaceSummary,)}): A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression.. [optional] # noqa: E501 dimension (int): The dimension of the indexed vectors.. [optional] # noqa: E501 - index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index).. [optional] # noqa: E501 + index_fullness (float): The fullness of the index, regardless of whether a metadata filter expression was passed. The granularity of this metric is 10%. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. The index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index). . [optional] # noqa: E501 total_vector_count (int): The total number of vectors in the index, regardless of whether a metadata filter expression was passed. [optional] # noqa: E501 """ diff --git a/pinecone/core/data/client/model/fetch_response.py b/pinecone/core/data/client/model/fetch_response.py index afa1a4959..9442d796b 100644 --- a/pinecone/core/data/client/model/fetch_response.py +++ b/pinecone/core/data/client/model/fetch_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/list_item.py b/pinecone/core/data/client/model/list_item.py index 2955ea0da..8360e1b12 100644 --- a/pinecone/core/data/client/model/list_item.py +++ b/pinecone/core/data/client/model/list_item.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/list_response.py b/pinecone/core/data/client/model/list_response.py index 8b331afa7..3cddc43d4 100644 --- a/pinecone/core/data/client/model/list_response.py +++ b/pinecone/core/data/client/model/list_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/namespace_summary.py b/pinecone/core/data/client/model/namespace_summary.py index d0100655a..cf518d88a 100644 --- a/pinecone/core/data/client/model/namespace_summary.py +++ b/pinecone/core/data/client/model/namespace_summary.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/pagination.py b/pinecone/core/data/client/model/pagination.py index 58231c1e7..86e19f456 100644 --- a/pinecone/core/data/client/model/pagination.py +++ b/pinecone/core/data/client/model/pagination.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/protobuf_any.py b/pinecone/core/data/client/model/protobuf_any.py index 844b862a0..ae923e320 100644 --- a/pinecone/core/data/client/model/protobuf_any.py +++ b/pinecone/core/data/client/model/protobuf_any.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/protobuf_null_value.py b/pinecone/core/data/client/model/protobuf_null_value.py index ced00cbf9..d96bc6b8c 100644 --- a/pinecone/core/data/client/model/protobuf_null_value.py +++ b/pinecone/core/data/client/model/protobuf_null_value.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/query_request.py b/pinecone/core/data/client/model/query_request.py index 6fe6f52cf..c611495eb 100644 --- a/pinecone/core/data/client/model/query_request.py +++ b/pinecone/core/data/client/model/query_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/query_response.py b/pinecone/core/data/client/model/query_response.py index 1c6425c13..f48907e43 100644 --- a/pinecone/core/data/client/model/query_response.py +++ b/pinecone/core/data/client/model/query_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/query_vector.py b/pinecone/core/data/client/model/query_vector.py index 2f6dec113..bb3e7c27d 100644 --- a/pinecone/core/data/client/model/query_vector.py +++ b/pinecone/core/data/client/model/query_vector.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/rpc_status.py b/pinecone/core/data/client/model/rpc_status.py index 3be73765d..b59946ee1 100644 --- a/pinecone/core/data/client/model/rpc_status.py +++ b/pinecone/core/data/client/model/rpc_status.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/scored_vector.py b/pinecone/core/data/client/model/scored_vector.py index 0cfe503fa..5c0fe6f83 100644 --- a/pinecone/core/data/client/model/scored_vector.py +++ b/pinecone/core/data/client/model/scored_vector.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/single_query_results.py b/pinecone/core/data/client/model/single_query_results.py index 34fb7a489..f85019d18 100644 --- a/pinecone/core/data/client/model/single_query_results.py +++ b/pinecone/core/data/client/model/single_query_results.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/sparse_values.py b/pinecone/core/data/client/model/sparse_values.py index d0f839d64..e391c8480 100644 --- a/pinecone/core/data/client/model/sparse_values.py +++ b/pinecone/core/data/client/model/sparse_values.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/update_request.py b/pinecone/core/data/client/model/update_request.py index 1b92db2d2..cefbbf01f 100644 --- a/pinecone/core/data/client/model/update_request.py +++ b/pinecone/core/data/client/model/update_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/upsert_request.py b/pinecone/core/data/client/model/upsert_request.py index 78d8b91e3..1480c515a 100644 --- a/pinecone/core/data/client/model/upsert_request.py +++ b/pinecone/core/data/client/model/upsert_request.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/upsert_response.py b/pinecone/core/data/client/model/upsert_response.py index b4376c528..031424f38 100644 --- a/pinecone/core/data/client/model/upsert_response.py +++ b/pinecone/core/data/client/model/upsert_response.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/usage.py b/pinecone/core/data/client/model/usage.py index 34ab7b185..3d50c53b5 100644 --- a/pinecone/core/data/client/model/usage.py +++ b/pinecone/core/data/client/model/usage.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model/vector.py b/pinecone/core/data/client/model/vector.py index f617fbef7..14ac8e96c 100644 --- a/pinecone/core/data/client/model/vector.py +++ b/pinecone/core/data/client/model/vector.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/model_utils.py b/pinecone/core/data/client/model_utils.py index abb0094a3..d51821159 100644 --- a/pinecone/core/data/client/model_utils.py +++ b/pinecone/core/data/client/model_utils.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/data/client/rest.py b/pinecone/core/data/client/rest.py index 0919f6ba9..2618c1874 100644 --- a/pinecone/core/data/client/rest.py +++ b/pinecone/core/data/client/rest.py @@ -3,7 +3,7 @@ Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - The version of the OpenAPI document: 2024-04 + The version of the OpenAPI document: 2024-07 Contact: support@pinecone.io Generated by: https://openapi-generator.tech """ diff --git a/pinecone/core/grpc/protos/vector_service_pb2.py b/pinecone/core/grpc/protos/vector_service_pb2.py index 378065d64..f9ffc212a 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.py +++ b/pinecone/core/grpc/protos/vector_service_pb2.py @@ -15,8 +15,12 @@ from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from protoc_gen_openapiv2.options import annotations_pb2 as protoc__gen__openapiv2_dot_options_dot_annotations__pb2 +from google.api import ( + field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2, +) +from protoc_gen_openapiv2.options import ( + annotations_pb2 as protoc__gen__openapiv2_dot_options_dot_annotations__pb2, +) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( diff --git a/pinecone/core/grpc/protos/vector_service_pb2.pyi b/pinecone/core/grpc/protos/vector_service_pb2.pyi index ca6e70d3c..827c301c0 100644 --- a/pinecone/core/grpc/protos/vector_service_pb2.pyi +++ b/pinecone/core/grpc/protos/vector_service_pb2.pyi @@ -23,16 +23,23 @@ class SparseValues(google.protobuf.message.Message): INDICES_FIELD_NUMBER: builtins.int VALUES_FIELD_NUMBER: builtins.int @property - def indices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def indices( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... @property - def values(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + def values( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... def __init__( self, *, indices: collections.abc.Iterable[builtins.int] | None = ..., values: collections.abc.Iterable[builtins.float] | None = ..., ) -> None: ... - def ClearField(self, field_name: typing.Literal["indices", b"indices", "values", b"values"]) -> None: ... + def ClearField( + self, + field_name: typing.Literal["indices", b"indices", "values", b"values"], + ) -> None: ... global___SparseValues = SparseValues @@ -47,7 +54,9 @@ class Vector(google.protobuf.message.Message): id: builtins.str """This is the vector's unique id.""" @property - def values(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + def values( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: """This is the vector data included in the request.""" @property @@ -65,12 +74,20 @@ class Vector(google.protobuf.message.Message): metadata: google.protobuf.struct_pb2.Struct | None = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"] + self, + field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"], ) -> builtins.bool: ... def ClearField( self, field_name: typing.Literal[ - "id", b"id", "metadata", b"metadata", "sparse_values", b"sparse_values", "values", b"values" + "id", + b"id", + "metadata", + b"metadata", + "sparse_values", + b"sparse_values", + "values", + b"values", ], ) -> None: ... @@ -90,7 +107,9 @@ class ScoredVector(google.protobuf.message.Message): score: builtins.float """This is a measure of similarity between this vector and the query vector. The higher the score, the more they are similar.""" @property - def values(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + def values( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: """This is the vector data, if it is requested.""" @property @@ -111,7 +130,8 @@ class ScoredVector(google.protobuf.message.Message): metadata: google.protobuf.struct_pb2.Struct | None = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"] + self, + field_name: typing.Literal["metadata", b"metadata", "sparse_values", b"sparse_values"], ) -> builtins.bool: ... def ClearField( self, @@ -158,17 +178,32 @@ class RequestUnion(google.protobuf.message.Message): def HasField( self, field_name: typing.Literal[ - "RequestUnionInner", b"RequestUnionInner", "delete", b"delete", "update", b"update", "upsert", b"upsert" + "RequestUnionInner", + b"RequestUnionInner", + "delete", + b"delete", + "update", + b"update", + "upsert", + b"upsert", ], ) -> builtins.bool: ... def ClearField( self, field_name: typing.Literal[ - "RequestUnionInner", b"RequestUnionInner", "delete", b"delete", "update", b"update", "upsert", b"upsert" + "RequestUnionInner", + b"RequestUnionInner", + "delete", + b"delete", + "update", + b"update", + "upsert", + b"upsert", ], ) -> None: ... def WhichOneof( - self, oneof_group: typing.Literal["RequestUnionInner", b"RequestUnionInner"] + self, + oneof_group: typing.Literal["RequestUnionInner", b"RequestUnionInner"], ) -> typing.Literal["upsert", "delete", "update"] | None: ... global___RequestUnion = RequestUnion @@ -184,7 +219,9 @@ class UpsertRequest(google.protobuf.message.Message): namespace: builtins.str """This is the namespace name where you upsert vectors.""" @property - def vectors(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Vector]: + def vectors( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Vector]: """An array containing the vectors to upsert. Recommended batch limit is 100 vectors.""" def __init__( @@ -193,7 +230,10 @@ class UpsertRequest(google.protobuf.message.Message): vectors: collections.abc.Iterable[global___Vector] | None = ..., namespace: builtins.str = ..., ) -> None: ... - def ClearField(self, field_name: typing.Literal["namespace", b"namespace", "vectors", b"vectors"]) -> None: ... + def ClearField( + self, + field_name: typing.Literal["namespace", b"namespace", "vectors", b"vectors"], + ) -> None: ... global___UpsertRequest = UpsertRequest @@ -230,7 +270,9 @@ class DeleteRequest(google.protobuf.message.Message): namespace: builtins.str """The namespace to delete vectors from, if applicable.""" @property - def ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + def ids( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """Vectors to delete.""" @property @@ -252,7 +294,14 @@ class DeleteRequest(google.protobuf.message.Message): def ClearField( self, field_name: typing.Literal[ - "delete_all", b"delete_all", "filter", b"filter", "ids", b"ids", "namespace", b"namespace" + "delete_all", + b"delete_all", + "filter", + b"filter", + "ids", + b"ids", + "namespace", + b"namespace", ], ) -> None: ... @@ -280,7 +329,9 @@ class FetchRequest(google.protobuf.message.Message): NAMESPACE_FIELD_NUMBER: builtins.int namespace: builtins.str @property - def ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + def ids( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """The vector IDs to fetch. Does not accept values containing spaces.""" def __init__( @@ -289,7 +340,10 @@ class FetchRequest(google.protobuf.message.Message): ids: collections.abc.Iterable[builtins.str] | None = ..., namespace: builtins.str = ..., ) -> None: ... - def ClearField(self, field_name: typing.Literal["ids", b"ids", "namespace", b"namespace"]) -> None: ... + def ClearField( + self, + field_name: typing.Literal["ids", b"ids", "namespace", b"namespace"], + ) -> None: ... global___FetchRequest = FetchRequest @@ -323,7 +377,9 @@ class FetchResponse(google.protobuf.message.Message): namespace: builtins.str """The namespace of the vectors.""" @property - def vectors(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Vector]: + def vectors( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Vector]: """The fetched vectors, in the form of a map between the fetched ids and the fetched vectors""" @property @@ -337,11 +393,21 @@ class FetchResponse(google.protobuf.message.Message): namespace: builtins.str = ..., usage: global___Usage | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"]) -> builtins.bool: ... + def HasField( + self, + field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"], + ) -> builtins.bool: ... def ClearField( self, field_name: typing.Literal[ - "_usage", b"_usage", "namespace", b"namespace", "usage", b"usage", "vectors", b"vectors" + "_usage", + b"_usage", + "namespace", + b"namespace", + "usage", + b"usage", + "vectors", + b"vectors", ], ) -> None: ... def WhichOneof(self, oneof_group: typing.Literal["_usage", b"_usage"]) -> typing.Literal["usage"] | None: ... @@ -413,7 +479,8 @@ class ListRequest(google.protobuf.message.Message): def WhichOneof(self, oneof_group: typing.Literal["_limit", b"_limit"]) -> typing.Literal["limit"] | None: ... @typing.overload def WhichOneof( - self, oneof_group: typing.Literal["_pagination_token", b"_pagination_token"] + self, + oneof_group: typing.Literal["_pagination_token", b"_pagination_token"], ) -> typing.Literal["pagination_token"] | None: ... @typing.overload def WhichOneof(self, oneof_group: typing.Literal["_prefix", b"_prefix"]) -> typing.Literal["prefix"] | None: ... @@ -463,7 +530,9 @@ class ListResponse(google.protobuf.message.Message): namespace: builtins.str """The namespace of the vectors.""" @property - def vectors(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ListItem]: + def vectors( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ListItem]: """A list of ids""" @property @@ -485,7 +554,14 @@ class ListResponse(google.protobuf.message.Message): def HasField( self, field_name: typing.Literal[ - "_pagination", b"_pagination", "_usage", b"_usage", "pagination", b"pagination", "usage", b"usage" + "_pagination", + b"_pagination", + "_usage", + b"_usage", + "pagination", + b"pagination", + "usage", + b"usage", ], ) -> builtins.bool: ... def ClearField( @@ -530,7 +606,9 @@ class QueryVector(google.protobuf.message.Message): namespace: builtins.str """An override the namespace to search.""" @property - def values(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + def values( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: """The query vector values. This should be the same length as the dimension of the index being queried.""" @property @@ -551,7 +629,8 @@ class QueryVector(google.protobuf.message.Message): filter: google.protobuf.struct_pb2.Struct | None = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["filter", b"filter", "sparse_values", b"sparse_values"] + self, + field_name: typing.Literal["filter", b"filter", "sparse_values", b"sparse_values"], ) -> builtins.bool: ... def ClearField( self, @@ -601,11 +680,15 @@ class QueryRequest(google.protobuf.message.Message): """The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.""" @property - def queries(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___QueryVector]: + def queries( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___QueryVector]: """DEPRECATED. The query vectors. Each `query()` request can contain only one of the parameters `queries`, `vector`, or `id`.""" @property - def vector(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + def vector( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: """The query vector. This should be the same length as the dimension of the index being queried. Each `query()` request can contain only one of the parameters `id` or `vector`.""" @property @@ -626,7 +709,8 @@ class QueryRequest(google.protobuf.message.Message): id: builtins.str = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["filter", b"filter", "sparse_vector", b"sparse_vector"] + self, + field_name: typing.Literal["filter", b"filter", "sparse_vector", b"sparse_vector"], ) -> builtins.bool: ... def ClearField( self, @@ -665,7 +749,9 @@ class SingleQueryResults(google.protobuf.message.Message): namespace: builtins.str """The namespace for the vectors.""" @property - def matches(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: + def matches( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: """The matches for the vectors.""" def __init__( @@ -674,7 +760,10 @@ class SingleQueryResults(google.protobuf.message.Message): matches: collections.abc.Iterable[global___ScoredVector] | None = ..., namespace: builtins.str = ..., ) -> None: ... - def ClearField(self, field_name: typing.Literal["matches", b"matches", "namespace", b"namespace"]) -> None: ... + def ClearField( + self, + field_name: typing.Literal["matches", b"matches", "namespace", b"namespace"], + ) -> None: ... global___SingleQueryResults = SingleQueryResults @@ -697,7 +786,9 @@ class QueryResponse(google.protobuf.message.Message): """DEPRECATED. The results of each query. The order is the same as `QueryRequest.queries`.""" @property - def matches(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: + def matches( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScoredVector]: """The matches for the vectors.""" @property @@ -712,7 +803,10 @@ class QueryResponse(google.protobuf.message.Message): namespace: builtins.str = ..., usage: global___Usage | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"]) -> builtins.bool: ... + def HasField( + self, + field_name: typing.Literal["_usage", b"_usage", "usage", b"usage"], + ) -> builtins.bool: ... def ClearField( self, field_name: typing.Literal[ @@ -745,10 +839,12 @@ class Usage(google.protobuf.message.Message): read_units: builtins.int | None = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"] + self, + field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"], ) -> builtins.bool: ... def ClearField( - self, field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"] + self, + field_name: typing.Literal["_read_units", b"_read_units", "read_units", b"read_units"], ) -> None: ... def WhichOneof( self, oneof_group: typing.Literal["_read_units", b"_read_units"] @@ -772,7 +868,9 @@ class UpdateRequest(google.protobuf.message.Message): namespace: builtins.str """Namespace name where to update the vector.""" @property - def values(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + def values( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: """Vector data.""" @property @@ -791,7 +889,8 @@ class UpdateRequest(google.protobuf.message.Message): namespace: builtins.str = ..., ) -> None: ... def HasField( - self, field_name: typing.Literal["set_metadata", b"set_metadata", "sparse_values", b"sparse_values"] + self, + field_name: typing.Literal["set_metadata", b"set_metadata", "sparse_values", b"sparse_values"], ) -> builtins.bool: ... def ClearField( self, @@ -902,7 +1001,9 @@ class DescribeIndexStatsResponse(google.protobuf.message.Message): total_vector_count: builtins.int """The total number of vectors in the index, regardless of whether a metadata filter expression was passed""" @property - def namespaces(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___NamespaceSummary]: + def namespaces( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___NamespaceSummary]: """A mapping for each namespace in the index from the namespace name to a summary of its contents. If a metadata filter expression is present, the summary will reflect only vectors matching that expression. diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 44379ad3b..8adaed504 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -4,9 +4,9 @@ from pinecone.config import ConfigBuilder -from pinecone.core.client.models import SparseValues -from pinecone.core.client import ApiClient -from pinecone.core.client.models import ( +from pinecone.core.data.client.models import SparseValues +from pinecone.core.data.client import ApiClient +from pinecone.core.data.client.models import ( FetchResponse, QueryRequest, QueryResponse, @@ -23,7 +23,7 @@ DescribeIndexStatsRequest, ListResponse, ) -from pinecone.core.client.api.data_plane_api import DataPlaneApi +from pinecone.core.data.client.api.data_plane_api import DataPlaneApi from ..utils import setup_openapi_client from .vector_factory import VectorFactory @@ -79,7 +79,12 @@ def __init__( openapi_config=None, **kwargs, ): - self._config = ConfigBuilder.build(api_key=api_key, host=host, additional_headers=additional_headers, **kwargs) + self._config = ConfigBuilder.build( + api_key=api_key, + host=host, + additional_headers=additional_headers, + **kwargs, + ) openapi_config = ConfigBuilder.build_openapi_config(self._config, openapi_config) self._vector_api = setup_openapi_client( @@ -172,7 +177,11 @@ def upsert( 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") + 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) @@ -209,7 +218,11 @@ def _iter_dataframe(df, batch_size): yield batch def upsert_from_dataframe( - self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True + self, + df, + namespace: Optional[str] = None, + batch_size: int = 500, + show_progress: bool = True, ) -> UpsertResponse: """Upserts a dataframe into the index. @@ -229,7 +242,11 @@ def 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") + 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) @@ -288,7 +305,12 @@ def delete( """ _check_type = kwargs.pop("_check_type", False) args_dict = self._parse_non_empty_args( - [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter)] + [ + ("ids", ids), + ("delete_all", delete_all), + ("namespace", namespace), + ("filter", filter), + ] ) return self._vector_api.delete( @@ -419,7 +441,12 @@ def update( self, id: str, values: Optional[List[float]] = None, - set_metadata: Optional[Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, + set_metadata: Optional[ + Dict[ + str, + Union[str, float, int, bool, List[int], List[float], List[str]], + ] + ] = None, namespace: Optional[str] = None, sparse_values: Optional[Union[SparseValues, Dict[str, Union[List[float], List[int]]]]] = None, **kwargs, @@ -477,7 +504,9 @@ def update( @validate_and_convert_errors def describe_index_stats( - self, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs + self, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + **kwargs, ) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. diff --git a/pinecone/data/sparse_vector_factory.py b/pinecone/data/sparse_vector_factory.py index 7376e8725..5b2379a49 100644 --- a/pinecone/data/sparse_vector_factory.py +++ b/pinecone/data/sparse_vector_factory.py @@ -5,9 +5,13 @@ from ..utils import convert_to_list -from .errors import SparseValuesTypeError, SparseValuesMissingKeysError, SparseValuesDictionaryExpectedError +from .errors import ( + SparseValuesTypeError, + SparseValuesMissingKeysError, + SparseValuesDictionaryExpectedError, +) -from pinecone.core.client.models import SparseValues +from pinecone.core.data.client.models import SparseValues class SparseValuesFactory: diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index fddcf4d65..1d1fbf468 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -7,7 +7,7 @@ from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS from .sparse_vector_factory import SparseValuesFactory -from pinecone.core.client.models import Vector, SparseValues +from pinecone.core.data.client.models import Vector, SparseValues from .errors import ( VectorDictionaryMissingKeysError, @@ -39,7 +39,12 @@ def _tuple_to_vector(item, check_type: bool) -> Vector: "Sparse values are not supported in tuples. Please use either dicts or Vector objects as inputs." ) else: - return Vector(id=id, values=convert_to_list(values), metadata=metadata or {}, _check_type=check_type) + return Vector( + id=id, + values=convert_to_list(values), + metadata=metadata or {}, + _check_type=check_type, + ) @staticmethod def _dict_to_vector(item, check_type: bool) -> Vector: diff --git a/pinecone/exceptions.py b/pinecone/exceptions/__init__.py similarity index 61% rename from pinecone/exceptions.py rename to pinecone/exceptions/__init__.py index dfe564c6a..20332a7bf 100644 --- a/pinecone/exceptions.py +++ b/pinecone/exceptions/__init__.py @@ -1,4 +1,4 @@ -from .core.client.exceptions import ( +from .openapi_exceptions import ( PineconeException, PineconeApiAttributeError, PineconeApiTypeError, @@ -10,20 +10,11 @@ ForbiddenException, ServiceException, ) - - -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) - +from .exceptions import ( + PineconeConfigurationError, + PineconeProtocolError, + ListConversionException, +) __all__ = [ "PineconeConfigurationError", @@ -39,4 +30,4 @@ def __init__(self, message): "ForbiddenException", "ServiceException", "ListConversionException", -] +] \ No newline at end of file diff --git a/pinecone/exceptions/exceptions.py b/pinecone/exceptions/exceptions.py new file mode 100644 index 000000000..c0117c7a5 --- /dev/null +++ b/pinecone/exceptions/exceptions.py @@ -0,0 +1,16 @@ +from .openapi_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/exceptions/openapi_exceptions.py b/pinecone/exceptions/openapi_exceptions.py new file mode 100644 index 000000000..cd6fa470e --- /dev/null +++ b/pinecone/exceptions/openapi_exceptions.py @@ -0,0 +1,150 @@ +# These exceptions are copied out of the generated openapi client code. +# They have been copied here so that we can have a single source of truth +# for exceptions and avoid having multiple classes with the same name +# as we generate more packages from the openapi specs. + +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): + """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): + """ + 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): + """ + 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): + """ + 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): + 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})\n" "Reason: {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): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=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/grpc/base.py b/pinecone/grpc/base.py index 75fe4a647..8fda5879d 100644 --- a/pinecone/grpc/base.py +++ b/pinecone/grpc/base.py @@ -15,7 +15,7 @@ from .config import GRPCClientConfig from pinecone.utils.constants import MAX_MSG_SIZE, REQUEST_ID, CLIENT_VERSION from pinecone.utils.user_agent import get_user_agent_grpc -from pinecone.exceptions import PineconeException +from pinecone.exceptions.exceptions import PineconeException _logger = logging.getLogger(__name__) @@ -41,7 +41,11 @@ def __init__( self.grpc_client_config = grpc_config or GRPCClientConfig() self.retry_config = self.grpc_client_config.retry_config or RetryConfig() - self.fixed_metadata = {"api-key": config.api_key, "service-name": index_name, "client-version": CLIENT_VERSION} + self.fixed_metadata = { + "api-key": config.api_key, + "service-name": index_name, + "client-version": CLIENT_VERSION, + } if self.grpc_client_config.additional_metadata: self.fixed_metadata.update(self.grpc_client_config.additional_metadata) @@ -103,7 +107,10 @@ def _gen_channel(self, options=None): user_provided_options = options or {} _options = tuple((k, v) for k, v in {**default_options, **user_provided_options}.items()) _logger.debug( - "creating new channel with endpoint %s options %s and config %s", target, _options, self.grpc_client_config + "creating new channel with endpoint %s options %s and config %s", + target, + _options, + self.grpc_client_config, ) if not self.grpc_client_config.secure: channel = grpc.insecure_channel(target, options=_options) @@ -138,13 +145,25 @@ def close(self): pass def _wrap_grpc_call( - self, func, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None + self, + func, + request, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, ): @wraps(func) def wrapped(): user_provided_metadata = metadata or {} _metadata = tuple( - (k, v) for k, v in {**self.fixed_metadata, **self._request_metadata(), **user_provided_metadata}.items() + (k, v) + for k, v in { + **self.fixed_metadata, + **self._request_metadata(), + **user_provided_metadata, + }.items() ) try: return func( diff --git a/pinecone/grpc/future.py b/pinecone/grpc/future.py index 160169d67..a4ea56b15 100644 --- a/pinecone/grpc/future.py +++ b/pinecone/grpc/future.py @@ -1,5 +1,5 @@ from grpc._channel import _MultiThreadedRendezvous -from pinecone.exceptions import PineconeException +from pinecone.exceptions.exceptions import PineconeException class PineconeGrpcFuture: diff --git a/pinecone/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index cbca6f995..5bafaee22 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -5,15 +5,23 @@ from tqdm.autonotebook import tqdm -from .utils import dict_to_proto_struct, parse_fetch_response, parse_query_response, parse_stats_response +from .utils import ( + dict_to_proto_struct, + parse_fetch_response, + parse_query_response, + parse_stats_response, +) from .vector_factory_grpc import VectorFactoryGRPC -from pinecone.core.client.models import ( +from pinecone.core.data.client.models import ( FetchResponse, QueryResponse, DescribeIndexStatsResponse, ) -from pinecone.models.list_response import ListResponse as SimpleListResponse, Pagination +from pinecone.models.list_response import ( + ListResponse as SimpleListResponse, + Pagination, +) from pinecone.core.grpc.protos.vector_service_pb2 import ( Vector as GRPCVector, QueryVector as GRPCQueryVector, @@ -138,10 +146,19 @@ def upsert( 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") + 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) + 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 @@ -149,7 +166,11 @@ def upsert( return UpsertResponse(upserted_count=total_upserted) def _upsert_batch( - self, vectors: List[GRPCVector], namespace: Optional[str], timeout: Optional[float], **kwargs + self, + vectors: List[GRPCVector], + namespace: Optional[str], + timeout: Optional[float], + **kwargs, ) -> UpsertResponse: args_dict = self._parse_non_empty_args([("namespace", namespace)]) request = UpsertRequest(vectors=vectors, **args_dict) @@ -183,10 +204,18 @@ def 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") + 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) + res = self.upsert( + vectors=chunk, + namespace=namespace, + async_req=use_async_requests, + ) pbar.update(len(chunk)) results.append(res) @@ -194,7 +223,11 @@ def upsert_from_dataframe( cast_results = cast(List[PineconeGrpcFuture], results) results = [ async_result.result() - for async_result in tqdm(cast_results, disable=not show_progress, desc="collecting async responses") + for async_result in tqdm( + cast_results, + disable=not show_progress, + desc="collecting async responses", + ) ] upserted_count = 0 @@ -257,7 +290,12 @@ def delete( filter_struct = None args_dict = self._parse_non_empty_args( - [("ids", ids), ("delete_all", delete_all), ("namespace", namespace), ("filter", filter_struct)] + [ + ("ids", ids), + ("delete_all", delete_all), + ("namespace", namespace), + ("filter", filter_struct), + ] ) timeout = kwargs.pop("timeout", None) @@ -268,7 +306,12 @@ def delete( else: return self._wrap_grpc_call(self.stub.Delete, request, timeout=timeout) - def fetch(self, ids: Optional[List[str]], namespace: Optional[str] = None, **kwargs) -> FetchResponse: + def fetch( + self, + ids: Optional[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. @@ -378,7 +421,12 @@ def update( id: str, async_req: bool = False, values: Optional[List[float]] = None, - set_metadata: Optional[Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, + set_metadata: Optional[ + Dict[ + str, + Union[str, float, int, bool, List[int], List[float], List[str]], + ] + ] = None, namespace: Optional[str] = None, sparse_values: Optional[Union[GRPCSparseValues, SparseVectorTypedDict]] = None, **kwargs, @@ -528,7 +576,9 @@ def list(self, **kwargs): done = True def describe_index_stats( - self, filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs + self, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, + **kwargs, ) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. diff --git a/pinecone/grpc/sparse_values_factory.py b/pinecone/grpc/sparse_values_factory.py index 8844bfd2a..d6e602b87 100644 --- a/pinecone/grpc/sparse_values_factory.py +++ b/pinecone/grpc/sparse_values_factory.py @@ -5,7 +5,11 @@ from ..utils import convert_to_list -from ..data import SparseValuesTypeError, SparseValuesMissingKeysError, SparseValuesDictionaryExpectedError +from ..data import ( + SparseValuesTypeError, + SparseValuesMissingKeysError, + SparseValuesDictionaryExpectedError, +) from pinecone.core.grpc.protos.vector_service_pb2 import ( SparseValues as GRPCSparseValues, diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index 87af9842e..e3720a365 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -7,7 +7,7 @@ def _generate_request_id() -> str: return str(uuid.uuid4()) -from pinecone.core.client.models import ( +from pinecone.core.data.client.models import ( Vector as _Vector, Usage, ScoredVector, @@ -52,7 +52,10 @@ def parse_fetch_response(response: dict): ) return FetchResponse( - vectors=vd, namespace=namespace, usage=parse_usage(response.get("usage", {})), _check_type=False + vectors=vd, + namespace=namespace, + usage=parse_usage(response.get("usage", {})), + _check_type=False, ) @@ -76,7 +79,11 @@ def parse_query_response(response: dict, _check_type: bool = False): # 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} + args = { + "namespace": response.get("namespace", ""), + "matches": matches, + "_check_type": _check_type, + } usage = response.get("usage") if usage: args["usage"] = parse_usage(usage) diff --git a/pinecone/grpc/vector_factory_grpc.py b/pinecone/grpc/vector_factory_grpc.py index a1717d830..b2529bae7 100644 --- a/pinecone/grpc/vector_factory_grpc.py +++ b/pinecone/grpc/vector_factory_grpc.py @@ -20,7 +20,10 @@ Vector as GRPCVector, SparseValues as GRPCSparseValues, ) -from pinecone import Vector as NonGRPCVector, SparseValues as NonGRPCSparseValues +from pinecone import ( + Vector as NonGRPCVector, + SparseValues as NonGRPCSparseValues, +) class VectorFactoryGRPC: @@ -30,12 +33,22 @@ def build(item: Union[GRPCVector, NonGRPCVector, Tuple, Dict]) -> GRPCVector: return item elif isinstance(item, NonGRPCVector): if item.sparse_values: - sv = GRPCSparseValues(indices=item.sparse_values.indices, values=item.sparse_values.values) + sv = GRPCSparseValues( + indices=item.sparse_values.indices, + values=item.sparse_values.values, + ) return GRPCVector( - id=item.id, values=item.values, metadata=dict_to_proto_struct(item.metadata or {}), sparse_values=sv + 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 {})) + 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): @@ -53,7 +66,11 @@ def _tuple_to_vector(item) -> GRPCVector: "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 {})) + return GRPCVector( + id=id, + values=convert_to_list(values), + metadata=dict_to_proto_struct(metadata or {}), + ) @staticmethod def _dict_to_vector(item) -> GRPCVector: diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py index 6acf8d658..e15ce43e4 100644 --- a/pinecone/models/__init__.py +++ b/pinecone/models/__init__.py @@ -1,4 +1,9 @@ -from .index_description import IndexDescription, IndexStatus, ServerlessSpecDefinition, PodSpecDefinition +from .index_description import ( + IndexDescription, + IndexStatus, + ServerlessSpecDefinition, + PodSpecDefinition, +) from .collection_description import CollectionDescription from .serverless_spec import ServerlessSpec from .pod_spec import PodSpec diff --git a/pinecone/models/collection_list.py b/pinecone/models/collection_list.py index 8d69d542e..2d0b9e1b2 100644 --- a/pinecone/models/collection_list.py +++ b/pinecone/models/collection_list.py @@ -1,4 +1,6 @@ -from pinecone.core.client.models import CollectionList as OpenAPICollectionList +from pinecone.core.control.client.models import ( + CollectionList as OpenAPICollectionList, +) class CollectionList: diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py index 21fc4444d..6fa5aaf51 100644 --- a/pinecone/models/index_list.py +++ b/pinecone/models/index_list.py @@ -1,4 +1,4 @@ -from pinecone.core.client.models import IndexList as OpenAPIIndexList +from pinecone.core.control.client.models import IndexList as OpenAPIIndexList class IndexList: diff --git a/pinecone/utils/__init__.py b/pinecone/utils/__init__.py index 640fdf636..ae884122f 100644 --- a/pinecone/utils/__init__.py +++ b/pinecone/utils/__init__.py @@ -5,5 +5,8 @@ from .fix_tuple_length import fix_tuple_length from .convert_to_list import convert_to_list from .normalize_host import normalize_host -from .setup_openapi_client import setup_openapi_client, build_plugin_setup_client +from .setup_openapi_client import ( + setup_openapi_client, + build_plugin_setup_client, +) from .docslinks import docslinks diff --git a/pinecone/utils/check_kwargs.py b/pinecone/utils/check_kwargs.py index 9c9cd330b..17038b1ec 100644 --- a/pinecone/utils/check_kwargs.py +++ b/pinecone/utils/check_kwargs.py @@ -6,4 +6,7 @@ def check_kwargs(caller, given): argspec = inspect.getfullargspec(caller) diff = set(given).difference(argspec.args) if diff: - logging.exception(caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), exc_info=False) + logging.exception( + caller.__name__ + " had unexpected keyword argument(s): " + ", ".join(diff), + exc_info=False, + ) diff --git a/pinecone/utils/convert_to_list.py b/pinecone/utils/convert_to_list.py index 9bd999232..521ee6922 100644 --- a/pinecone/utils/convert_to_list.py +++ b/pinecone/utils/convert_to_list.py @@ -1,4 +1,4 @@ -from ..exceptions import ListConversionException +from ..exceptions.exceptions import ListConversionException def convert_to_list(obj): diff --git a/pinecone/utils/setup_openapi_client.py b/pinecone/utils/setup_openapi_client.py index 10dd53f7a..8ea1f7b37 100644 --- a/pinecone/utils/setup_openapi_client.py +++ b/pinecone/utils/setup_openapi_client.py @@ -2,7 +2,15 @@ import copy -def setup_openapi_client(api_client_klass, api_klass, config, openapi_config, pool_threads, api_version=None, **kwargs): +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 @@ -29,7 +37,13 @@ def setup_openapi_client(api_client_klass, api_klass, config, openapi_config, po 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 + api_client_klass, + api_klass, + config, + openapi_config, + pool_threads, + api_version, + **kwargs, ) return setup_plugin_client diff --git a/pinecone/utils/user_agent.py b/pinecone/utils/user_agent.py index 8ff89e4d5..a0fc7af32 100644 --- a/pinecone/utils/user_agent.py +++ b/pinecone/utils/user_agent.py @@ -20,7 +20,10 @@ def _build_source_tag_field(source_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 = "{} ({})".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 diff --git a/tests/integration/data/test_openapi_configuration.py b/tests/integration/data/test_openapi_configuration.py index 26c12a038..d4e19cd59 100644 --- a/tests/integration/data/test_openapi_configuration.py +++ b/tests/integration/data/test_openapi_configuration.py @@ -2,7 +2,7 @@ import os from pinecone import Pinecone -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration from urllib3 import make_headers diff --git a/tests/unit/models/test_collection_list.py b/tests/unit/models/test_collection_list.py index 22e1b0288..49338fa4f 100644 --- a/tests/unit/models/test_collection_list.py +++ b/tests/unit/models/test_collection_list.py @@ -1,6 +1,6 @@ import pytest from pinecone import CollectionList -from pinecone.core.client.models import CollectionList as OpenApiCollectionList, CollectionModel +from pinecone.core.control.client.models import CollectionList as OpenApiCollectionList, CollectionModel @pytest.fixture diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py index 1bcc6d2f7..57ccabd6c 100644 --- a/tests/unit/models/test_index_list.py +++ b/tests/unit/models/test_index_list.py @@ -1,6 +1,6 @@ import pytest from pinecone import IndexList -from pinecone.core.client.models import IndexList as OpenApiIndexList +from pinecone.core.control.client.models import IndexList as OpenApiIndexList @pytest.fixture diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 6eaf4f48e..4ad5bb697 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,7 +1,7 @@ from pinecone import Pinecone -from pinecone.exceptions import PineconeConfigurationError +from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config import PineconeConfig -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration import pytest import os diff --git a/tests/unit/test_config_builder.py b/tests/unit/test_config_builder.py index 84d3c7dd0..c6f26859a 100644 --- a/tests/unit/test_config_builder.py +++ b/tests/unit/test_config_builder.py @@ -1,6 +1,6 @@ import pytest -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration from pinecone.config import ConfigBuilder from pinecone import PineconeConfigurationError diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 228e20d6c..42359b724 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -1,10 +1,10 @@ import pytest import re -from unittest.mock import patch +from unittest.mock import patch, MagicMock from pinecone import ConfigBuilder, Pinecone, PodSpec, ServerlessSpec -from pinecone.core.client.models import IndexList, IndexModel -from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.control.client.models import IndexList, IndexModel +from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration import time @@ -118,6 +118,20 @@ def test_create_index_with_timeout( assert p.index_api.describe_index.call_count == expected_describe_index_calls assert time.sleep.call_count == expected_sleep_calls + @pytest.mark.parametrize('index_spec', [ + {"serverless": {"cloud": "aws", "region": "us-west1"}}, + {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1, "replicas": 1, "shards": 1}}, + ]) + def test_create_index(self, mocker, index_spec): + p = Pinecone(api_key="123-456-789") + + mock_api = MagicMock() + mocker.patch.object(p, "index_api", mock_api) + + p.create_index(name="my-index", dimension=10, spec=index_spec) + + mock_api.create_index.assert_called_once() + @pytest.mark.parametrize( "timeout_value, describe_index_responses, expected_describe_index_calls, expected_sleep_calls", [ @@ -171,7 +185,6 @@ def test_api_key_and_openapi_config(self, mocker): p = Pinecone(api_key="123", openapi_config=OpenApiConfiguration.get_default_copy()) assert p.config.api_key == "123" - class TestIndexConfig: def test_default_pool_threads(self): pc = Pinecone(api_key="123-456-789") diff --git a/tests/unit/utils/test_setup_openapi_client.py b/tests/unit/utils/test_setup_openapi_client.py index e4e77df40..39555e7f7 100644 --- a/tests/unit/utils/test_setup_openapi_client.py +++ b/tests/unit/utils/test_setup_openapi_client.py @@ -1,8 +1,8 @@ import pytest import re from pinecone.config import ConfigBuilder -from pinecone.core.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.client.api_client import ApiClient +from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.control.client.api_client import ApiClient from pinecone.utils.setup_openapi_client import setup_openapi_client, build_plugin_setup_client From e13d34c68856c7cc5fc22a13a1852710081d01df Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 13:22:47 -0400 Subject: [PATCH 06/13] Do post-generation surgery to build pinecone.core.shared --- codegen/apis | 2 +- codegen/build-oas.sh | 67 +- pinecone/config/config.py | 2 +- pinecone/config/openapi.py | 2 +- pinecone/control/index_host_store.py | 2 +- pinecone/control/pinecone.py | 2 +- pinecone/core/control/client/__init__.py | 16 +- .../core/control/client/api/inference_api.py | 4 +- .../control/client/api/manage_indexes_api.py | 4 +- pinecone/core/control/client/exceptions.py | 156 -- .../control/client/model/collection_list.py | 6 +- .../control/client/model/collection_model.py | 6 +- .../client/model/configure_index_request.py | 6 +- .../model/configure_index_request_spec.py | 6 +- .../model/configure_index_request_spec_pod.py | 6 +- .../client/model/create_collection_request.py | 6 +- .../client/model/create_index_request.py | 6 +- .../control/client/model/embed_request.py | 6 +- .../client/model/embed_request_inputs.py | 6 +- .../client/model/embed_request_parameters.py | 6 +- .../core/control/client/model/embedding.py | 6 +- .../control/client/model/embeddings_list.py | 6 +- .../client/model/embeddings_list_usage.py | 6 +- .../core/control/client/model/index_list.py | 6 +- .../core/control/client/model/index_model.py | 6 +- .../control/client/model/index_model_spec.py | 6 +- .../client/model/index_model_status.py | 6 +- .../core/control/client/model/index_spec.py | 6 +- .../client/model/inline_response401.py | 6 +- .../client/model/inline_response401_error.py | 6 +- .../core/control/client/model/pod_spec.py | 6 +- .../client/model/pod_spec_metadata_config.py | 6 +- .../control/client/model/serverless_spec.py | 6 +- pinecone/core/control/client/model_utils.py | 1886 ----------------- pinecone/core/control/client/rest.py | 404 ---- pinecone/core/data/client/__init__.py | 16 +- .../core/data/client/api/data_plane_api.py | 4 +- pinecone/core/data/client/api_client.py | 847 -------- pinecone/core/data/client/configuration.py | 487 ----- pinecone/core/data/client/exceptions.py | 156 -- .../core/data/client/model/delete_request.py | 6 +- .../model/describe_index_stats_request.py | 6 +- .../model/describe_index_stats_response.py | 6 +- .../core/data/client/model/fetch_response.py | 6 +- pinecone/core/data/client/model/list_item.py | 6 +- .../core/data/client/model/list_response.py | 6 +- .../data/client/model/namespace_summary.py | 6 +- pinecone/core/data/client/model/pagination.py | 6 +- .../core/data/client/model/protobuf_any.py | 6 +- .../data/client/model/protobuf_null_value.py | 6 +- .../core/data/client/model/query_request.py | 6 +- .../core/data/client/model/query_response.py | 6 +- .../core/data/client/model/query_vector.py | 6 +- pinecone/core/data/client/model/rpc_status.py | 6 +- .../core/data/client/model/scored_vector.py | 6 +- .../data/client/model/single_query_results.py | 6 +- .../core/data/client/model/sparse_values.py | 6 +- .../core/data/client/model/update_request.py | 6 +- .../core/data/client/model/upsert_request.py | 6 +- .../core/data/client/model/upsert_response.py | 6 +- pinecone/core/data/client/model/usage.py | 6 +- pinecone/core/data/client/model/vector.py | 6 +- .../{control/client => shared}/api_client.py | 18 +- .../client => shared}/configuration.py | 12 +- .../shared/exceptions.py} | 5 - .../{data/client => shared}/model_utils.py | 12 +- pinecone/core/{data/client => shared}/rest.py | 12 +- pinecone/exceptions/__init__.py | 2 +- pinecone/exceptions/exceptions.py | 2 +- .../data/test_openapi_configuration.py | 2 +- tests/unit/test_config.py | 2 +- tests/unit/test_config_builder.py | 2 +- tests/unit/test_control.py | 2 +- tests/unit/utils/test_setup_openapi_client.py | 2 +- 74 files changed, 232 insertions(+), 4168 deletions(-) delete mode 100644 pinecone/core/control/client/exceptions.py delete mode 100644 pinecone/core/control/client/model_utils.py delete mode 100644 pinecone/core/control/client/rest.py delete mode 100644 pinecone/core/data/client/api_client.py delete mode 100644 pinecone/core/data/client/configuration.py delete mode 100644 pinecone/core/data/client/exceptions.py rename pinecone/core/{control/client => shared}/api_client.py (98%) rename pinecone/core/{control/client => shared}/configuration.py (97%) rename pinecone/{exceptions/openapi_exceptions.py => core/shared/exceptions.py} (94%) rename pinecone/core/{data/client => shared}/model_utils.py (99%) rename pinecone/core/{data/client => shared}/rest.py (97%) diff --git a/codegen/apis b/codegen/apis index 4de44568f..307ad3ba9 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 4de44568f98556d29e8044c8146b572d2396cb05 +Subproject commit 307ad3ba99a41a08b566616cfc028cf5c0a1d989 diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 1f1203f51..85049132b 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -eux -o pipefail + version='2024-07' rm -rf build @@ -62,17 +64,55 @@ generate_client() { --template-dir "/workspace/$template_dir" } -# Adjust exception import paths in generated code -adjust_exception_imports() { - local client_dir=$1 - local exception_dir=$2 - - find pinecone/core -name "*.py" -exec sed -i 's/from pinecone\.core\.control\.client\.exceptions/from pinecone\.exceptions/g' {} + - - - # Adjust import paths in exceptions - sed -i '' -e 's/from pinecone\.core\.exceptions/from pinecone.core.control.exceptions/g' $exception_dir/__init__.py - sed -i '' -e 's/from pinecone\.core\.exceptions/from pinecone.core.data.exceptions/g' $exception_dir/__init__.py +extract_shared_classes() { + rm -rf pinecone/core/shared + mkdir -p pinecone/core/shared + + # Define the list of source files + sharedFiles=( + "api_client.py" + "configuration.py" + "exceptions.py" + "model_utils.py" + "rest.py" + ) + + control_directory="pinecone/core/control/client" + data_directory="pinecone/core/data/client" + target_directory="pinecone/core/shared" + + # Create the target directory if it does not exist + mkdir -p "$target_directory" + + # Loop through each file and copy it to the target directory + for file in "${sharedFiles[@]}"; do + mv "$control_directory/$file" "$target_directory" + rm "$data_directory/$file" + done + + # Remove the docstring headers that aren't really correct in the + # context of this new shared package structure + find "$target_directory" -name "*.py" -print0 | xargs -0 -I {} sh -c 'sed -i "" "/^\"\"\"/,/^\"\"\"/d" "{}"' + + echo "All shared files have been copied to $target_directory." + + # Adjust import paths in every file + find pinecone/core -name "*.py" | while IFS= read -r file; do + sed -i '' 's/from \.\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" + sed -i '' 's/from pinecone\.core\.control\.client import rest/from pinecone\.core\.shared import rest/g' "$file" + + sed -i '' 's/from pinecone\.core\.control\.client\.api_client/from pinecone\.core\.shared\.api_client/g' "$file" + sed -i '' 's/from pinecone\.core\.control\.client\.configuration/from pinecone\.core\.shared\.configuration/g' "$file" + sed -i '' 's/from pinecone\.core\.control\.client\.exceptions/from pinecone\.core\.shared\.exceptions/g' "$file" + sed -i '' 's/from pinecone\.core\.control\.client\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" + sed -i '' 's/from pinecone\.core\.control\.client\.rest/from pinecone\.core\.shared\.rest/g' "$file" + + sed -i '' 's/from pinecone\.core\.data\.client\.api_client/from pinecone\.core\.shared\.api_client/g' "$file" + sed -i '' 's/from pinecone\.core\.data\.client\.configuration/from pinecone\.core\.shared\.configuration/g' "$file" + sed -i '' 's/from pinecone\.core\.data\.client\.exceptions/from pinecone\.core\.shared\.exceptions/g' "$file" + sed -i '' 's/from pinecone\.core\.data\.client\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" + sed -i '' 's/from pinecone\.core\.data\.client\.rest/from pinecone\.core\.shared\.rest/g' "$file" + done } update_apis_repo @@ -94,5 +134,10 @@ generate_client $control_oas $control_config rm -rf pinecone/core/control cp -r build/pinecone/core/control pinecone/core/control +# Even though we want to generate multiple packages, we +# don't want to duplicate every exception and utility class. +# So we do a bit of surgery to combine the shared files. +extract_shared_classes + # Format generated files poetry run black pinecone/core diff --git a/pinecone/config/config.py b/pinecone/config/config.py index da906a6b3..7546d3d0e 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -3,7 +3,7 @@ from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config.openapi import OpenApiConfigFactory -from pinecone.core.control.client.configuration import ( +from pinecone.core.shared.configuration import ( Configuration as OpenApiConfiguration, ) from pinecone.utils import normalize_host diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index 4e56b2908..b12d438d6 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -7,7 +7,7 @@ from urllib3.connection import HTTPConnection -from pinecone.core.control.client.configuration import ( +from pinecone.core.shared.configuration import ( Configuration as OpenApiConfiguration, ) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index ffde835b9..ea6c3510e 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -3,7 +3,7 @@ from pinecone.core.control.client.api.manage_indexes_api import ( ManageIndexesApi as IndexOperationsApi, ) -from pinecone.core.control.client.exceptions import PineconeException +from pinecone.core.shared.exceptions import PineconeException from pinecone.utils import normalize_host diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 89f01f528..eec971c78 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -10,7 +10,7 @@ from pinecone.core.control.client.api.manage_indexes_api import ( ManageIndexesApi, ) -from pinecone.core.control.client.api_client import ApiClient +from pinecone.core.shared.api_client import ApiClient from pinecone.utils import ( normalize_host, diff --git a/pinecone/core/control/client/__init__.py b/pinecone/core/control/client/__init__.py index 1f0f51445..0e28e94db 100644 --- a/pinecone/core/control/client/__init__.py +++ b/pinecone/core/control/client/__init__.py @@ -14,15 +14,15 @@ __version__ = "1.0.0" # import ApiClient -from pinecone.core.control.client.api_client import ApiClient +from pinecone.core.shared.api_client import ApiClient # import Configuration -from pinecone.core.control.client.configuration import Configuration +from pinecone.core.shared.configuration import Configuration # import exceptions -from pinecone.core.control.client.exceptions import PineconeException -from pinecone.core.control.client.exceptions import PineconeApiAttributeError -from pinecone.core.control.client.exceptions import PineconeApiTypeError -from pinecone.core.control.client.exceptions import PineconeApiValueError -from pinecone.core.control.client.exceptions import PineconeApiKeyError -from pinecone.core.control.client.exceptions import PineconeApiException +from pinecone.core.shared.exceptions import PineconeException +from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.shared.exceptions import PineconeApiTypeError +from pinecone.core.shared.exceptions import PineconeApiValueError +from pinecone.core.shared.exceptions import PineconeApiKeyError +from pinecone.core.shared.exceptions import PineconeApiException diff --git a/pinecone/core/control/client/api/inference_api.py b/pinecone/core/control/client/api/inference_api.py index ac9564c16..adc95ac69 100644 --- a/pinecone/core/control/client/api/inference_api.py +++ b/pinecone/core/control/client/api/inference_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, diff --git a/pinecone/core/control/client/api/manage_indexes_api.py b/pinecone/core/control/client/api/manage_indexes_api.py index 43d7eb356..e560b7feb 100644 --- a/pinecone/core/control/client/api/manage_indexes_api.py +++ b/pinecone/core/control/client/api/manage_indexes_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, diff --git a/pinecone/core/control/client/exceptions.py b/pinecone/core/control/client/exceptions.py deleted file mode 100644 index ede69833a..000000000 --- a/pinecone/core/control/client/exceptions.py +++ /dev/null @@ -1,156 +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 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -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): - """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): - """ - 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): - """ - 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): - """ - 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): - 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})\n" "Reason: {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): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=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/core/control/client/model/collection_list.py b/pinecone/core/control/client/model/collection_list.py index 151307897..726b20b8f 100644 --- a/pinecone/core/control/client/model/collection_list.py +++ b/pinecone/core/control/client/model/collection_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/collection_model.py b/pinecone/core/control/client/model/collection_model.py index 4689ce326..4b4184c85 100644 --- a/pinecone/core/control/client/model/collection_model.py +++ b/pinecone/core/control/client/model/collection_model.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class CollectionModel(ModelNormal): diff --git a/pinecone/core/control/client/model/configure_index_request.py b/pinecone/core/control/client/model/configure_index_request.py index 8917f9f56..0745cb299 100644 --- a/pinecone/core/control/client/model/configure_index_request.py +++ b/pinecone/core/control/client/model/configure_index_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/configure_index_request_spec.py b/pinecone/core/control/client/model/configure_index_request_spec.py index a3d4f7fc3..74a22d06f 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec.py +++ b/pinecone/core/control/client/model/configure_index_request_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/configure_index_request_spec_pod.py b/pinecone/core/control/client/model/configure_index_request_spec_pod.py index 5aa5c3d7b..e3b5ca1d7 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/control/client/model/configure_index_request_spec_pod.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class ConfigureIndexRequestSpecPod(ModelNormal): diff --git a/pinecone/core/control/client/model/create_collection_request.py b/pinecone/core/control/client/model/create_collection_request.py index e48210f54..a6cd13bb7 100644 --- a/pinecone/core/control/client/model/create_collection_request.py +++ b/pinecone/core/control/client/model/create_collection_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class CreateCollectionRequest(ModelNormal): diff --git a/pinecone/core/control/client/model/create_index_request.py b/pinecone/core/control/client/model/create_index_request.py index c229af885..f0e4d3826 100644 --- a/pinecone/core/control/client/model/create_index_request.py +++ b/pinecone/core/control/client/model/create_index_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/embed_request.py b/pinecone/core/control/client/model/embed_request.py index 5c26b145d..e577c172b 100644 --- a/pinecone/core/control/client/model/embed_request.py +++ b/pinecone/core/control/client/model/embed_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/embed_request_inputs.py b/pinecone/core/control/client/model/embed_request_inputs.py index f3cf16c22..08edc3d7a 100644 --- a/pinecone/core/control/client/model/embed_request_inputs.py +++ b/pinecone/core/control/client/model/embed_request_inputs.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class EmbedRequestInputs(ModelNormal): diff --git a/pinecone/core/control/client/model/embed_request_parameters.py b/pinecone/core/control/client/model/embed_request_parameters.py index fa32e1477..ff9f8b0a6 100644 --- a/pinecone/core/control/client/model/embed_request_parameters.py +++ b/pinecone/core/control/client/model/embed_request_parameters.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class EmbedRequestParameters(ModelNormal): diff --git a/pinecone/core/control/client/model/embedding.py b/pinecone/core/control/client/model/embedding.py index 8fe54a75f..c97ba2e4f 100644 --- a/pinecone/core/control/client/model/embedding.py +++ b/pinecone/core/control/client/model/embedding.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class Embedding(ModelNormal): diff --git a/pinecone/core/control/client/model/embeddings_list.py b/pinecone/core/control/client/model/embeddings_list.py index 3098052c2..6d2f70ebb 100644 --- a/pinecone/core/control/client/model/embeddings_list.py +++ b/pinecone/core/control/client/model/embeddings_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/embeddings_list_usage.py b/pinecone/core/control/client/model/embeddings_list_usage.py index 0bfe41c86..32ea91ec4 100644 --- a/pinecone/core/control/client/model/embeddings_list_usage.py +++ b/pinecone/core/control/client/model/embeddings_list_usage.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class EmbeddingsListUsage(ModelNormal): diff --git a/pinecone/core/control/client/model/index_list.py b/pinecone/core/control/client/model/index_list.py index 2aeea1d46..fcd23bb26 100644 --- a/pinecone/core/control/client/model/index_list.py +++ b/pinecone/core/control/client/model/index_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/index_model.py b/pinecone/core/control/client/model/index_model.py index cb6b64ece..c80080d7a 100644 --- a/pinecone/core/control/client/model/index_model.py +++ b/pinecone/core/control/client/model/index_model.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/index_model_spec.py b/pinecone/core/control/client/model/index_model_spec.py index 5dd42f89c..e4ef37804 100644 --- a/pinecone/core/control/client/model/index_model_spec.py +++ b/pinecone/core/control/client/model/index_model_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/index_model_status.py b/pinecone/core/control/client/model/index_model_status.py index 062c653b7..fa1a484ed 100644 --- a/pinecone/core/control/client/model/index_model_status.py +++ b/pinecone/core/control/client/model/index_model_status.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class IndexModelStatus(ModelNormal): diff --git a/pinecone/core/control/client/model/index_spec.py b/pinecone/core/control/client/model/index_spec.py index 8c93880a2..acc1e01a1 100644 --- a/pinecone/core/control/client/model/index_spec.py +++ b/pinecone/core/control/client/model/index_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/inline_response401.py b/pinecone/core/control/client/model/inline_response401.py index dd7dd9467..f98753c7c 100644 --- a/pinecone/core/control/client/model/inline_response401.py +++ b/pinecone/core/control/client/model/inline_response401.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/inline_response401_error.py b/pinecone/core/control/client/model/inline_response401_error.py index 4328e3374..9d3819029 100644 --- a/pinecone/core/control/client/model/inline_response401_error.py +++ b/pinecone/core/control/client/model/inline_response401_error.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class InlineResponse401Error(ModelNormal): diff --git a/pinecone/core/control/client/model/pod_spec.py b/pinecone/core/control/client/model/pod_spec.py index 0a995cada..63009568e 100644 --- a/pinecone/core/control/client/model/pod_spec.py +++ b/pinecone/core/control/client/model/pod_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/model/pod_spec_metadata_config.py b/pinecone/core/control/client/model/pod_spec_metadata_config.py index 69031c7df..f2d4200dd 100644 --- a/pinecone/core/control/client/model/pod_spec_metadata_config.py +++ b/pinecone/core/control/client/model/pod_spec_metadata_config.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class PodSpecMetadataConfig(ModelNormal): diff --git a/pinecone/core/control/client/model/serverless_spec.py b/pinecone/core/control/client/model/serverless_spec.py index 7c675b4cb..bad5b35bd 100644 --- a/pinecone/core/control/client/model/serverless_spec.py +++ b/pinecone/core/control/client/model/serverless_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.control.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.control.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class ServerlessSpec(ModelNormal): diff --git a/pinecone/core/control/client/model_utils.py b/pinecone/core/control/client/model_utils.py deleted file mode 100644 index c3d5b4115..000000000 --- a/pinecone/core/control/client/model_utils.py +++ /dev/null @@ -1,1886 +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 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -from datetime import date, datetime # noqa: F401 -import inspect -import io -import os -import pprint -import re -import tempfile - -from pinecone.core.control.client.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): - 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) != 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) - - 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 isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - # elif isinstance(input_value, datetime): - # # this must be higher than the date check because - # # isinstance(datetime_instance, date) == True - # return datetime - # elif isinstance(input_value, date): - # return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if isinstance(input_values, list) and not set(input_values).issubset(set(these_allowed_values)): - invalid_values = (", ".join(map(str, set(input_values) - set(these_allowed_values))),) - raise 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 == 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) != str: - raise get_type_error(inner_key, inner_path, valid_classes, key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration, - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: ( - (item[0], model_to_dict(item[1], serialize=serialize)) - if hasattr(item[1], "_data_store") - else item - ), - value.items(), - ) - ) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, "_data_store"): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = "value" - if key_type: - key_or_value = "key" - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = "Invalid type for variable '{0}'. Required {1} type {2} and " "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed""" - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return "is {0}".format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas["allOf"]: - - try: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise 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/core/control/client/rest.py b/pinecone/core/control/client/rest.py deleted file mode 100644 index 191a32080..000000000 --- a/pinecone/core/control/client/rest.py +++ /dev/null @@ -1,404 +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 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import io -import json -import logging -import re -import ssl -import os -from urllib.parse import urlencode - -import urllib3 - -from pinecone.core.control.client.exceptions import ( - PineconeApiException, - UnauthorizedException, - ForbiddenException, - NotFoundException, - ServiceException, - 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__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # 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. - """ - 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) - if ("Content-Type" not in headers) or (re.search("json", headers["Content-Type"], re.IGNORECASE)): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif headers["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 headers["Content-Type"] == "multipart/form-data": - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers["Content-Type"] - 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: - r = self.pool_manager.request( - method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers - ) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise PineconeApiException(status=0, reason=msg) - - if os.environ.get("PINECONE_DEBUG_CURL"): - o = RESTResponse(r) - - 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) - - # log response body - logger.debug("response body: %s", r.data) - - 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 - - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def OPTIONS( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): - return self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def POST( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PUT( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PATCH( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PATCH", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) diff --git a/pinecone/core/data/client/__init__.py b/pinecone/core/data/client/__init__.py index 1ed0378a5..4251eb3c3 100644 --- a/pinecone/core/data/client/__init__.py +++ b/pinecone/core/data/client/__init__.py @@ -14,15 +14,15 @@ __version__ = "1.0.0" # import ApiClient -from pinecone.core.data.client.api_client import ApiClient +from pinecone.core.shared.api_client import ApiClient # import Configuration -from pinecone.core.data.client.configuration import Configuration +from pinecone.core.shared.configuration import Configuration # import exceptions -from pinecone.core.data.client.exceptions import PineconeException -from pinecone.core.data.client.exceptions import PineconeApiAttributeError -from pinecone.core.data.client.exceptions import PineconeApiTypeError -from pinecone.core.data.client.exceptions import PineconeApiValueError -from pinecone.core.data.client.exceptions import PineconeApiKeyError -from pinecone.core.data.client.exceptions import PineconeApiException +from pinecone.core.shared.exceptions import PineconeException +from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.shared.exceptions import PineconeApiTypeError +from pinecone.core.shared.exceptions import PineconeApiValueError +from pinecone.core.shared.exceptions import PineconeApiKeyError +from pinecone.core.shared.exceptions import PineconeApiException diff --git a/pinecone/core/data/client/api/data_plane_api.py b/pinecone/core/data/client/api/data_plane_api.py index 26653ae5c..eff177296 100644 --- a/pinecone/core/data/client/api/data_plane_api.py +++ b/pinecone/core/data/client/api/data_plane_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, diff --git a/pinecone/core/data/client/api_client.py b/pinecone/core/data/client/api_client.py deleted file mode 100644 index 9d03d2729..000000000 --- a/pinecone/core/data/client/api_client.py +++ /dev/null @@ -1,847 +0,0 @@ -""" - Pinecone Data Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import json -import atexit -import mimetypes -from multiprocessing.pool import ThreadPool -import io -import os -import re -import typing -from urllib.parse import quote -from urllib3.fields import RequestField - - -from pinecone.core.data.client import rest -from pinecone.core.data.client.configuration import Configuration -from pinecone.core.data.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException -from pinecone.core.data.client.model_utils import ( - ModelNormal, - ModelSimple, - ModelComposed, - check_allowed_values, - check_validations, - date, - datetime, - deserialize_file, - file_type, - model_to_dict, - none_type, - validate_and_convert_types, -) - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - _pool = None - - def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1): - if configuration is None: - configuration = Configuration.get_default_copy() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - 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._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 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: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - ): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params["Cookie"] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param)) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) - post_params.extend(self.files_parameters(files)) - if header_params["Content-Type"].startswith("multipart"): - post_params = self.parameters_to_multipart(post_params, (dict)) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings, resource_path, method, body) - - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path - - try: - # perform request and return response - response_data = self.request( - method, - url, - query_params=query_params, - headers=header_params, - post_params=post_params, - body=body, - _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 - return return_data - - # deserialize response data - if response_type: - if response_type != (file_type,): - encoding = "utf-8" - content_type = response_data.getheader("content-type") - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - if match: - encoding = match.group(1) - response_data.data = response_data.data.decode(encoding) - - return_data = self.deserialize(response_data, response_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 parameters_to_multipart(self, params, collection_types): - """Get parameters as list of tuples, formatting as json if value is collection_types - - :param params: Parameters as list of two-tuples - :param dict collection_types: Parameter collection types - :return: Parameters as list of tuple or urllib3.fields.RequestField - """ - new_params = [] - if collection_types is None: - collection_types = dict - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json - v = json.dumps(v, ensure_ascii=False).encode("utf-8") - field = RequestField(k, v) - field.make_multipart(content_type="application/json; charset=utf-8") - new_params.append(field) - else: - new_params.append((k, v)) - return new_params - - @classmethod - def sanitize_for_serialization(cls, obj): - """Prepares data for transmission before it is sent with the rest client - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - 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, none_type, bool)): - 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__)) - - def deserialize(self, response, response_type, _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, self.configuration, 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=self.configuration - ) - return deserialized_data - - def call_api( - self, - resource_path: str, - method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - async_req: typing.Optional[bool] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - ): - """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 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`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """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 = [] - 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 - - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data - - def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.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) - filedata = self.get_file_data_and_close_file(file_instance) - mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" - params.append(tuple([param_name, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """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) - - def select_header_content_type(self, content_types): - """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] - - def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - :param resource_path: A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method. - :param body: A object representing the body of the HTTP request. - The object type is the return value of _encoder.default(). - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting["in"] == "cookie": - headers["Cookie"] = auth_setting["value"] - elif auth_setting["in"] == "header": - if auth_setting["type"] != "http-signature": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - querys.append((auth_setting["key"], auth_setting["value"])) - else: - raise PineconeApiValueError("Authentication token must be in `query` or `header`") - - -class Endpoint(object): - def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None): - """Creates an endpoint - - Args: - settings (dict): see below key value pairs - 'response_type' (tuple/None): response type - 'auth' (list): a list of auth type keys - 'endpoint_path' (str): the endpoint path - 'operation_id' (str): endpoint string identifier - 'http_method' (str): POST/PUT/PATCH/GET etc - 'servers' (list): list of str servers that this endpoint is at - params_map (dict): see below key value pairs - 'all' (list): list of str endpoint parameter names - 'required' (list): list of required parameter names - 'nullable' (list): list of nullable parameter names - 'enum' (list): list of parameters with enum values - 'validation' (list): list of parameters with validations - root_map - 'validations' (dict): the dict mapping endpoint parameter tuple - paths to their validation dictionaries - 'allowed_values' (dict): the dict mapping endpoint parameter - tuple paths to their allowed_values (enum) dictionaries - 'openapi_types' (dict): param_name to openapi type - 'attribute_map' (dict): param_name to camelCase name - 'location_map' (dict): param_name to 'body', 'file', 'form', - 'header', 'path', 'query' - collection_format_map (dict): param_name to `csv` etc. - headers_map (dict): see below key value pairs - 'accept' (list): list of Accept header strings - 'content_type' (list): list of Content-Type header strings - api_client (ApiClient) api client instance - callable (function): the function which is invoked when the - Endpoint is called - """ - self.settings = settings - self.params_map = params_map - self.params_map["all"].extend( - [ - "async_req", - "_host_index", - "_preload_content", - "_request_timeout", - "_return_http_data_only", - "_check_input_type", - "_check_return_type", - ] - ) - self.params_map["nullable"].extend(["_request_timeout"]) - self.validations = root_map["validations"] - self.allowed_values = root_map["allowed_values"] - self.openapi_types = root_map["openapi_types"] - extra_types = { - "async_req": (bool,), - "_host_index": (none_type, int), - "_preload_content": (bool,), - "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]), - "_return_http_data_only": (bool,), - "_check_input_type": (bool,), - "_check_return_type": (bool,), - } - self.openapi_types.update(extra_types) - self.attribute_map = root_map["attribute_map"] - self.location_map = root_map["location_map"] - self.collection_format_map = root_map["collection_format_map"] - self.headers_map = headers_map - self.api_client = api_client - self.callable = callable - - def __validate_inputs(self, kwargs): - for param in self.params_map["enum"]: - if param in kwargs: - check_allowed_values(self.allowed_values, (param,), kwargs[param]) - - for param in self.params_map["validation"]: - if param in kwargs: - check_validations( - self.validations, (param,), kwargs[param], configuration=self.api_client.configuration - ) - - if kwargs["_check_input_type"] is False: - return - - for key, value in kwargs.items(): - fixed_val = validate_and_convert_types( - value, - self.openapi_types[key], - [key], - False, - kwargs["_check_input_type"], - configuration=self.api_client.configuration, - ) - kwargs[key] = fixed_val - - def __gather_params(self, kwargs): - params = {"body": None, "collection_format": {}, "file": {}, "form": [], "header": {}, "path": {}, "query": []} - - for param_name, param_value in kwargs.items(): - param_location = self.location_map.get(param_name) - if param_location is None: - continue - if param_location: - if param_location == "body": - params["body"] = param_value - continue - base_name = self.attribute_map[param_name] - if param_location == "form" and self.openapi_types[param_name] == (file_type,): - params["file"][param_name] = [param_value] - elif param_location == "form" and self.openapi_types[param_name] == ([file_type],): - # param_value is already a list - params["file"][param_name] = param_value - elif param_location in {"form", "query"}: - param_value_full = (base_name, param_value) - params[param_location].append(param_value_full) - if param_location not in {"form", "query"}: - params[param_location][base_name] = param_value - collection_format = self.collection_format_map.get(param_name) - if collection_format: - params["collection_format"][base_name] = collection_format - - return params - - def __call__(self, *args, **kwargs): - """This method is invoked when endpoints are called - Example: - - api_instance = DataPlaneApi() - api_instance.alt_delete # this is an instance of the class Endpoint - api_instance.alt_delete() # this invokes api_instance.alt_delete.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.alt_delete.callable or self.callable in this class - - """ - return self.callable(self, *args, **kwargs) - - def call_with_http_info(self, **kwargs): - - try: - index = ( - self.api_client.configuration.server_operation_index.get( - self.settings["operation_id"], self.api_client.configuration.server_index - ) - if kwargs["_host_index"] is None - else kwargs["_host_index"] - ) - server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings["operation_id"], self.api_client.configuration.server_variables - ) - _host = self.api_client.configuration.get_host_from_settings( - index, variables=server_variables, servers=self.settings["servers"] - ) - except IndexError: - if self.settings["servers"]: - raise PineconeApiValueError( - "Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"]) - ) - _host = None - - for key, value in kwargs.items(): - if key not in self.params_map["all"]: - raise PineconeApiTypeError( - "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.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 self.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, self.settings["operation_id"]) - ) - - for key in self.params_map["required"]: - if key not in kwargs.keys(): - raise PineconeApiValueError( - "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"]) - ) - - self.__validate_inputs(kwargs) - - params = self.__gather_params(kwargs) - - accept_headers_list = self.headers_map["accept"] - if accept_headers_list: - params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list) - - content_type_headers_list = self.headers_map["content_type"] - if content_type_headers_list: - header_list = self.api_client.select_header_content_type(content_type_headers_list) - params["header"]["Content-Type"] = header_list - - return self.api_client.call_api( - self.settings["endpoint_path"], - self.settings["http_method"], - params["path"], - params["query"], - params["header"], - body=params["body"], - post_params=params["form"], - files=params["file"], - response_type=self.settings["response_type"], - auth_settings=self.settings["auth"], - async_req=kwargs["async_req"], - _check_type=kwargs["_check_return_type"], - _return_http_data_only=kwargs["_return_http_data_only"], - _preload_content=kwargs["_preload_content"], - _request_timeout=kwargs["_request_timeout"], - _host=_host, - collection_formats=params["collection_format"], - ) diff --git a/pinecone/core/data/client/configuration.py b/pinecone/core/data/client/configuration.py deleted file mode 100644 index de009c460..000000000 --- a/pinecone/core/data/client/configuration.py +++ /dev/null @@ -1,487 +0,0 @@ -""" - Pinecone Data Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -from http import client as http_client -from pinecone.core.data.client.exceptions import PineconeApiValueError - - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "maxItems", - "minItems", -} - - -class Configuration(object): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param host: Base url - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer) - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication - :param password: Password for HTTP basic authentication - :param discard_unknown_keys: Boolean value indicating whether to discard - unknown properties. A server may send a response that includes additional - properties that are not known by the client in the following scenarios: - 1. The OpenAPI document is incomplete, i.e. it does not match the server - implementation. - 2. The client was generated using an older version of the OpenAPI document - and the server has been upgraded since then. - If a schema in the OpenAPI document defines the additionalProperties attribute, - then all undeclared properties received by the server are injected into the - additional properties map. In that case, there are undeclared properties, and - nothing to discard. - :param disabled_client_side_validations (string): Comma-separated list of - JSON schema validation keywords to disable JSON schema structural validation - rules. The following keywords may be specified: multipleOf, maximum, - exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, - maxItems, minItems. - By default, the validation is performed for data generated locally by the client - and data received from the server, independent of any validation performed by - the server side. If the input data does not satisfy the JSON schema validation - rules specified in the OpenAPI document, an exception is raised. - If disabled_client_side_validations is set, structural validation is - disabled. This can be useful to troubleshoot data validation problem, such as - when the OpenAPI document validation rules do not match the actual API data - received by the server. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format - - :Example: - - API Key Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - cookieAuth: # name for the security scheme - type: apiKey - in: cookie - name: JSESSIONID # cookie name - - You can programmatically set the cookie: - - conf = pinecone.core.data.client.Configuration( - api_key={'cookieAuth': 'abc123'} - api_key_prefix={'cookieAuth': 'JSESSIONID'} - ) - - The following cookie will be added to the HTTP request: - Cookie: JSESSIONID abc123 - """ - - _default = None - - def __init__( - self, - host=None, - api_key=None, - api_key_prefix=None, - access_token=None, - username=None, - password=None, - discard_unknown_keys=False, - disabled_client_side_validations="", - server_index=None, - server_variables=None, - server_operation_index=None, - server_operation_variables=None, - ssl_ca_cert=None, - ): - """Constructor""" - self._base_path = "https://unknown" 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.access_token = access_token - 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.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.discard_unknown_keys = discard_unknown_keys - self.disabled_client_side_validations = disabled_client_side_validations - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("pinecone.core.data.client") - 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 get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers(basic_auth=username + ":" + password).get("authorization") - - 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 to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return ( - "Python SDK Debug Report:\n" - "OS: {env}\n" - "Python Version: {pyversion}\n" - "Version of the API: 2024-07\n" - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - ) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - "url": "https://{index_host}", - "description": "No description provided", - "variables": { - "index_host": { - "description": "host of the index", - "default_value": "unknown", - } - }, - } - ] - - 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 diff --git a/pinecone/core/data/client/exceptions.py b/pinecone/core/data/client/exceptions.py deleted file mode 100644 index 54cb943c5..000000000 --- a/pinecone/core/data/client/exceptions.py +++ /dev/null @@ -1,156 +0,0 @@ -""" - Pinecone Data Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -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): - """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): - """ - 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): - """ - 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): - """ - 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): - 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})\n" "Reason: {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): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=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/core/data/client/model/delete_request.py b/pinecone/core/data/client/model/delete_request.py index c6d4e5d94..a8d09cbf9 100644 --- a/pinecone/core/data/client/model/delete_request.py +++ b/pinecone/core/data/client/model/delete_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class DeleteRequest(ModelNormal): diff --git a/pinecone/core/data/client/model/describe_index_stats_request.py b/pinecone/core/data/client/model/describe_index_stats_request.py index a383ef287..18da99dfb 100644 --- a/pinecone/core/data/client/model/describe_index_stats_request.py +++ b/pinecone/core/data/client/model/describe_index_stats_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class DescribeIndexStatsRequest(ModelNormal): diff --git a/pinecone/core/data/client/model/describe_index_stats_response.py b/pinecone/core/data/client/model/describe_index_stats_response.py index 7a643d882..27945d21e 100644 --- a/pinecone/core/data/client/model/describe_index_stats_response.py +++ b/pinecone/core/data/client/model/describe_index_stats_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/fetch_response.py b/pinecone/core/data/client/model/fetch_response.py index 9442d796b..1a3293d47 100644 --- a/pinecone/core/data/client/model/fetch_response.py +++ b/pinecone/core/data/client/model/fetch_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/list_item.py b/pinecone/core/data/client/model/list_item.py index 8360e1b12..ed3c7049a 100644 --- a/pinecone/core/data/client/model/list_item.py +++ b/pinecone/core/data/client/model/list_item.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class ListItem(ModelNormal): diff --git a/pinecone/core/data/client/model/list_response.py b/pinecone/core/data/client/model/list_response.py index 3cddc43d4..2cf84cda7 100644 --- a/pinecone/core/data/client/model/list_response.py +++ b/pinecone/core/data/client/model/list_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/namespace_summary.py b/pinecone/core/data/client/model/namespace_summary.py index cf518d88a..d9faed447 100644 --- a/pinecone/core/data/client/model/namespace_summary.py +++ b/pinecone/core/data/client/model/namespace_summary.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class NamespaceSummary(ModelNormal): diff --git a/pinecone/core/data/client/model/pagination.py b/pinecone/core/data/client/model/pagination.py index 86e19f456..485d37aef 100644 --- a/pinecone/core/data/client/model/pagination.py +++ b/pinecone/core/data/client/model/pagination.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class Pagination(ModelNormal): diff --git a/pinecone/core/data/client/model/protobuf_any.py b/pinecone/core/data/client/model/protobuf_any.py index ae923e320..fad28c252 100644 --- a/pinecone/core/data/client/model/protobuf_any.py +++ b/pinecone/core/data/client/model/protobuf_any.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class ProtobufAny(ModelNormal): diff --git a/pinecone/core/data/client/model/protobuf_null_value.py b/pinecone/core/data/client/model/protobuf_null_value.py index d96bc6b8c..f7d832578 100644 --- a/pinecone/core/data/client/model/protobuf_null_value.py +++ b/pinecone/core/data/client/model/protobuf_null_value.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class ProtobufNullValue(ModelSimple): diff --git a/pinecone/core/data/client/model/query_request.py b/pinecone/core/data/client/model/query_request.py index c611495eb..3989b9acd 100644 --- a/pinecone/core/data/client/model/query_request.py +++ b/pinecone/core/data/client/model/query_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/query_response.py b/pinecone/core/data/client/model/query_response.py index f48907e43..8b92d93c0 100644 --- a/pinecone/core/data/client/model/query_response.py +++ b/pinecone/core/data/client/model/query_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/query_vector.py b/pinecone/core/data/client/model/query_vector.py index bb3e7c27d..3e7b3efbb 100644 --- a/pinecone/core/data/client/model/query_vector.py +++ b/pinecone/core/data/client/model/query_vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/rpc_status.py b/pinecone/core/data/client/model/rpc_status.py index b59946ee1..2963f0bea 100644 --- a/pinecone/core/data/client/model/rpc_status.py +++ b/pinecone/core/data/client/model/rpc_status.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/scored_vector.py b/pinecone/core/data/client/model/scored_vector.py index 5c0fe6f83..0a92f52e5 100644 --- a/pinecone/core/data/client/model/scored_vector.py +++ b/pinecone/core/data/client/model/scored_vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/single_query_results.py b/pinecone/core/data/client/model/single_query_results.py index f85019d18..832a9751e 100644 --- a/pinecone/core/data/client/model/single_query_results.py +++ b/pinecone/core/data/client/model/single_query_results.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/sparse_values.py b/pinecone/core/data/client/model/sparse_values.py index e391c8480..b3b2439b4 100644 --- a/pinecone/core/data/client/model/sparse_values.py +++ b/pinecone/core/data/client/model/sparse_values.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class SparseValues(ModelNormal): diff --git a/pinecone/core/data/client/model/update_request.py b/pinecone/core/data/client/model/update_request.py index cefbbf01f..144ccc8c6 100644 --- a/pinecone/core/data/client/model/update_request.py +++ b/pinecone/core/data/client/model/update_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/upsert_request.py b/pinecone/core/data/client/model/upsert_request.py index 1480c515a..842009c46 100644 --- a/pinecone/core/data/client/model/upsert_request.py +++ b/pinecone/core/data/client/model/upsert_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/data/client/model/upsert_response.py b/pinecone/core/data/client/model/upsert_response.py index 031424f38..2d961e59a 100644 --- a/pinecone/core/data/client/model/upsert_response.py +++ b/pinecone/core/data/client/model/upsert_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class UpsertResponse(ModelNormal): diff --git a/pinecone/core/data/client/model/usage.py b/pinecone/core/data/client/model/usage.py index 3d50c53b5..26256809f 100644 --- a/pinecone/core/data/client/model/usage.py +++ b/pinecone/core/data/client/model/usage.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError class Usage(ModelNormal): diff --git a/pinecone/core/data/client/model/vector.py b/pinecone/core/data/client/model/vector.py index 14ac8e96c..987ed9f8f 100644 --- a/pinecone/core/data/client/model/vector.py +++ b/pinecone/core/data/client/model/vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.data.client.model_utils import ( # noqa: F401 +from pinecone.core.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from ..model_utils import OpenApiModel -from pinecone.core.data.client.exceptions import PineconeApiAttributeError +from pinecone.core.shared.model_utils import OpenApiModel +from pinecone.core.shared.exceptions import PineconeApiAttributeError def lazy_import(): diff --git a/pinecone/core/control/client/api_client.py b/pinecone/core/shared/api_client.py similarity index 98% rename from pinecone/core/control/client/api_client.py rename to pinecone/core/shared/api_client.py index 6f9032adf..d76e26e74 100644 --- a/pinecone/core/control/client/api_client.py +++ b/pinecone/core/shared/api_client.py @@ -1,13 +1,3 @@ -""" - Pinecone Control Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - import json import atexit import mimetypes @@ -20,10 +10,10 @@ from urllib3.fields import RequestField -from pinecone.core.control.client import rest -from pinecone.core.control.client.configuration import Configuration -from pinecone.core.control.client.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException -from pinecone.core.control.client.model_utils import ( +from pinecone.core.shared import rest +from pinecone.core.shared.configuration import Configuration +from pinecone.core.shared.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException +from pinecone.core.shared.model_utils import ( ModelNormal, ModelSimple, ModelComposed, diff --git a/pinecone/core/control/client/configuration.py b/pinecone/core/shared/configuration.py similarity index 97% rename from pinecone/core/control/client/configuration.py rename to pinecone/core/shared/configuration.py index f5b01dcd4..3653c30b9 100644 --- a/pinecone/core/control/client/configuration.py +++ b/pinecone/core/shared/configuration.py @@ -1,13 +1,3 @@ -""" - Pinecone Control Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - import copy import logging import multiprocessing @@ -15,7 +5,7 @@ import urllib3 from http import client as http_client -from pinecone.core.control.client.exceptions import PineconeApiValueError +from pinecone.core.shared.exceptions import PineconeApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { diff --git a/pinecone/exceptions/openapi_exceptions.py b/pinecone/core/shared/exceptions.py similarity index 94% rename from pinecone/exceptions/openapi_exceptions.py rename to pinecone/core/shared/exceptions.py index cd6fa470e..187a16786 100644 --- a/pinecone/exceptions/openapi_exceptions.py +++ b/pinecone/core/shared/exceptions.py @@ -1,8 +1,3 @@ -# These exceptions are copied out of the generated openapi client code. -# They have been copied here so that we can have a single source of truth -# for exceptions and avoid having multiple classes with the same name -# as we generate more packages from the openapi specs. - class PineconeException(Exception): """The base exception class for all exceptions in the Pinecone Python SDK""" diff --git a/pinecone/core/data/client/model_utils.py b/pinecone/core/shared/model_utils.py similarity index 99% rename from pinecone/core/data/client/model_utils.py rename to pinecone/core/shared/model_utils.py index d51821159..baf00e3b4 100644 --- a/pinecone/core/data/client/model_utils.py +++ b/pinecone/core/shared/model_utils.py @@ -1,13 +1,3 @@ -""" - Pinecone Data Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - from datetime import date, datetime # noqa: F401 import inspect import io @@ -16,7 +6,7 @@ import re import tempfile -from pinecone.core.data.client.exceptions import ( +from pinecone.core.shared.exceptions import ( PineconeApiKeyError, PineconeApiAttributeError, PineconeApiTypeError, diff --git a/pinecone/core/data/client/rest.py b/pinecone/core/shared/rest.py similarity index 97% rename from pinecone/core/data/client/rest.py rename to pinecone/core/shared/rest.py index 2618c1874..9e49b4f29 100644 --- a/pinecone/core/data/client/rest.py +++ b/pinecone/core/shared/rest.py @@ -1,13 +1,3 @@ -""" - Pinecone Data Plane API - - Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - import io import json import logging @@ -18,7 +8,7 @@ import urllib3 -from pinecone.core.data.client.exceptions import ( +from pinecone.core.shared.exceptions import ( PineconeApiException, UnauthorizedException, ForbiddenException, diff --git a/pinecone/exceptions/__init__.py b/pinecone/exceptions/__init__.py index 20332a7bf..f1e5e55fd 100644 --- a/pinecone/exceptions/__init__.py +++ b/pinecone/exceptions/__init__.py @@ -1,4 +1,4 @@ -from .openapi_exceptions import ( +from pinecone.core.shared.exceptions import ( PineconeException, PineconeApiAttributeError, PineconeApiTypeError, diff --git a/pinecone/exceptions/exceptions.py b/pinecone/exceptions/exceptions.py index c0117c7a5..81bcbd8cf 100644 --- a/pinecone/exceptions/exceptions.py +++ b/pinecone/exceptions/exceptions.py @@ -1,4 +1,4 @@ -from .openapi_exceptions import ( +from pinecone.core.shared.exceptions import ( PineconeException ) diff --git a/tests/integration/data/test_openapi_configuration.py b/tests/integration/data/test_openapi_configuration.py index d4e19cd59..59e68deb9 100644 --- a/tests/integration/data/test_openapi_configuration.py +++ b/tests/integration/data/test_openapi_configuration.py @@ -2,7 +2,7 @@ import os from pinecone import Pinecone -from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration from urllib3 import make_headers diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 4ad5bb697..3d03a0c54 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,7 +1,7 @@ from pinecone import Pinecone from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config import PineconeConfig -from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration import pytest import os diff --git a/tests/unit/test_config_builder.py b/tests/unit/test_config_builder.py index c6f26859a..445eea656 100644 --- a/tests/unit/test_config_builder.py +++ b/tests/unit/test_config_builder.py @@ -1,6 +1,6 @@ import pytest -from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration from pinecone.config import ConfigBuilder from pinecone import PineconeConfigurationError diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 42359b724..12ac400fb 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -4,7 +4,7 @@ from pinecone import ConfigBuilder, Pinecone, PodSpec, ServerlessSpec from pinecone.core.control.client.models import IndexList, IndexModel from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.control.client.configuration import Configuration as OpenApiConfiguration +from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration import time diff --git a/tests/unit/utils/test_setup_openapi_client.py b/tests/unit/utils/test_setup_openapi_client.py index 39555e7f7..b46e3bfe4 100644 --- a/tests/unit/utils/test_setup_openapi_client.py +++ b/tests/unit/utils/test_setup_openapi_client.py @@ -2,7 +2,7 @@ import re from pinecone.config import ConfigBuilder from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.control.client.api_client import ApiClient +from pinecone.core.shared.api_client import ApiClient from pinecone.utils.setup_openapi_client import setup_openapi_client, build_plugin_setup_client From e3a3c031353602cfdb319ae72cccbe8912fba2de Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 13:32:46 -0400 Subject: [PATCH 07/13] Refactoring in codegen script --- codegen/build-oas.sh | 55 ++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 85049132b..6fa018607 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -65,29 +65,34 @@ generate_client() { } extract_shared_classes() { - rm -rf pinecone/core/shared - mkdir -p pinecone/core/shared + target_directory="pinecone/core/shared" + rm -rf $target_directory + mkdir -p $target_directory + + modules=("control" "data") - # Define the list of source files + # Define the list of shared source files sharedFiles=( - "api_client.py" - "configuration.py" - "exceptions.py" - "model_utils.py" - "rest.py" + "api_client" + "configuration" + "exceptions" + "model_utils" + "rest" ) - control_directory="pinecone/core/control/client" - data_directory="pinecone/core/data/client" - target_directory="pinecone/core/shared" - - # Create the target directory if it does not exist - mkdir -p "$target_directory" + source_directory="pinecone/core/${modules[0]}/client" - # Loop through each file and copy it to the target directory + # Loop through each file we want to share and copy it to the target directory for file in "${sharedFiles[@]}"; do - mv "$control_directory/$file" "$target_directory" - rm "$data_directory/$file" + cp "$source_directory/$file.py" "$target_directory" + done + + # Cleanup shared files in each module + for module in "${modules[@]}"; do + source_directory="pinecone/core/$module/client" + for file in "${sharedFiles[@]}"; do + rm "$source_directory/$file.py" + done done # Remove the docstring headers that aren't really correct in the @@ -101,17 +106,11 @@ extract_shared_classes() { sed -i '' 's/from \.\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" sed -i '' 's/from pinecone\.core\.control\.client import rest/from pinecone\.core\.shared import rest/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client\.api_client/from pinecone\.core\.shared\.api_client/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client\.configuration/from pinecone\.core\.shared\.configuration/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client\.exceptions/from pinecone\.core\.shared\.exceptions/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client\.rest/from pinecone\.core\.shared\.rest/g' "$file" - - sed -i '' 's/from pinecone\.core\.data\.client\.api_client/from pinecone\.core\.shared\.api_client/g' "$file" - sed -i '' 's/from pinecone\.core\.data\.client\.configuration/from pinecone\.core\.shared\.configuration/g' "$file" - sed -i '' 's/from pinecone\.core\.data\.client\.exceptions/from pinecone\.core\.shared\.exceptions/g' "$file" - sed -i '' 's/from pinecone\.core\.data\.client\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" - sed -i '' 's/from pinecone\.core\.data\.client\.rest/from pinecone\.core\.shared\.rest/g' "$file" + for module in "${modules[@]}"; do + for sharedFile in "${sharedFiles[@]}"; do + sed -i '' "s/from pinecone\.core\.$module\.client\.$sharedFile/from pinecone\.core\.shared\.$sharedFile/g" "$file" + done + done done } From 416a0c615ac7cccade03c9de3a619935b476a7cb Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 14:08:53 -0400 Subject: [PATCH 08/13] More cleanup --- codegen/apis | 2 +- codegen/build-oas.sh | 78 +++++++++++++++++++++----------------------- 2 files changed, 38 insertions(+), 42 deletions(-) diff --git a/codegen/apis b/codegen/apis index 307ad3ba9..04a751307 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 307ad3ba99a41a08b566616cfc028cf5c0a1d989 +Subproject commit 04a7513074c893ee005004598cfbbbbad4f07138 diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 6fa018607..ea2772bbf 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -3,6 +3,9 @@ set -eux -o pipefail version='2024-07' +modules=("control" "data") + +destination="pinecone/core" rm -rf build mkdir build @@ -24,53 +27,58 @@ verify_spec_version() { exit 1 fi - if [ ! -d "codegen/apis/_build/$version" ]; then - echo "Version $version does not exist in apis build dir" + verify_directory_exists "codegen/apis/_build/${version}" +} + +verify_file_exists() { + local filename=$1 + if [ ! -f "$filename" ]; then + echo "File does not exist at $filename" exit 1 fi } -verify_spec_file_exists() { - local oas_file=$1 - if [ ! -f "$oas_file" ]; then - echo "Spec file does not exist at $oas_file" +verify_directory_exists() { + local directory=$1 + if [ ! -d "$directory" ]; then + echo "Directory does not exist at $directory" exit 1 fi } generate_client() { - local oas_file=$1 - local openapi_generator_config=$2 - local template_dir="codegen/python-oas-templates/templates5.2.0" + local module_name=$1 - if [ ! -f "$oas_file" ]; then - echo "Spec file does not exist at $oas_file" - exit 1 - fi - if [ ! -d "$template_dir" ]; then - echo "Template directory does not exist at $template_dir" - exit 1 - fi + oas_file="codegen/apis/_build/${version}/${module_name}_${version}.oas.yaml" + openapi_generator_config="codegen/openapi-config.${module_name}.json" + template_dir="codegen/python-oas-templates/templates5.2.0" + + verify_file_exists $oas_file + verify_file_exists $openapi_generator_config + verify_directory_exists $template_dir # Cleanup previous build files echo "Cleaning up previous build files" rm -rf build + # Generate client module docker run --rm -v $(pwd):/workspace openapitools/openapi-generator-cli:v5.2.0 generate \ --input-spec "/workspace/$oas_file" \ --generator-name python \ --config "/workspace/$openapi_generator_config" \ --output /workspace/build \ --template-dir "/workspace/$template_dir" + + # Copy the generated module to the correct location + rm -rf "${destination}/${module_name}" + cp -r "build/pinecone/core/${module_name}" "${destination}/${module_name}" } extract_shared_classes() { - target_directory="pinecone/core/shared" + target_directory="${destination}/shared" rm -rf $target_directory mkdir -p $target_directory - modules=("control" "data") - # Define the list of shared source files sharedFiles=( "api_client" @@ -80,18 +88,18 @@ extract_shared_classes() { "rest" ) - source_directory="pinecone/core/${modules[0]}/client" + source_directory="${destination}/${modules[0]}/client" # Loop through each file we want to share and copy it to the target directory for file in "${sharedFiles[@]}"; do - cp "$source_directory/$file.py" "$target_directory" + cp "${source_directory}/${file}.py" "$target_directory" done # Cleanup shared files in each module for module in "${modules[@]}"; do - source_directory="pinecone/core/$module/client" + source_directory="${destination}/${module}/client" for file in "${sharedFiles[@]}"; do - rm "$source_directory/$file.py" + rm "${source_directory}/${file}.py" done done @@ -102,7 +110,7 @@ extract_shared_classes() { echo "All shared files have been copied to $target_directory." # Adjust import paths in every file - find pinecone/core -name "*.py" | while IFS= read -r file; do + find "${destination}" -name "*.py" | while IFS= read -r file; do sed -i '' 's/from \.\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" sed -i '' 's/from pinecone\.core\.control\.client import rest/from pinecone\.core\.shared import rest/g' "$file" @@ -117,21 +125,9 @@ extract_shared_classes() { update_apis_repo verify_spec_version $version -# Generate data plane client -data_oas="codegen/apis/_build/$version/data_$version.oas.yaml" -data_config="codegen/openapi-config.data.json" -verify_spec_file_exists $data_oas -generate_client $data_oas $data_config -rm -rf pinecone/core/data -cp -r build/pinecone/core/data pinecone/core/data - -# Generate control plane client -control_oas="codegen/apis/_build/$version/control_$version.oas.yaml" -control_config="codegen/openapi-config.control.json" -verify_spec_file_exists $control_oas -generate_client $control_oas $control_config -rm -rf pinecone/core/control -cp -r build/pinecone/core/control pinecone/core/control +for module in "${modules[@]}"; do + generate_client $module +done # Even though we want to generate multiple packages, we # don't want to duplicate every exception and utility class. @@ -139,4 +135,4 @@ cp -r build/pinecone/core/control pinecone/core/control extract_shared_classes # Format generated files -poetry run black pinecone/core +poetry run black "${destination}" From 1424c8dda1bfc5a5000ec89e417d0610e801ed35 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 17:00:40 -0400 Subject: [PATCH 09/13] Adjust package structure --- codegen/build-oas.sh | 21 +-- codegen/openapi-config.control.json | 2 +- codegen/openapi-config.data.json | 2 +- pinecone/__init__.py | 2 +- pinecone/config/config.py | 2 +- pinecone/config/openapi.py | 2 +- pinecone/control/index_host_store.py | 4 +- pinecone/control/pinecone.py | 6 +- pinecone/core/control/__init__.py | 0 pinecone/core/control/client/__init__.py | 28 ---- .../core/control/client/models/__init__.py | 34 ---- pinecone/core/data/__init__.py | 0 pinecone/core/data/client/__init__.py | 28 ---- pinecone/core/data/client/models/__init__.py | 33 ---- pinecone/core/openapi/control/__init__.py | 28 ++++ .../control}/api/__init__.py | 2 +- .../control}/api/inference_api.py | 10 +- .../control}/api/manage_indexes_api.py | 20 +-- .../control}/apis/__init__.py | 4 +- .../control}/model/__init__.py | 0 .../control}/model/collection_list.py | 8 +- .../control}/model/collection_model.py | 6 +- .../control}/model/configure_index_request.py | 8 +- .../model/configure_index_request_spec.py | 8 +- .../model/configure_index_request_spec_pod.py | 6 +- .../model/create_collection_request.py | 6 +- .../control}/model/create_index_request.py | 8 +- .../control}/model/embed_request.py | 10 +- .../control}/model/embed_request_inputs.py | 6 +- .../model/embed_request_parameters.py | 6 +- .../control}/model/embedding.py | 6 +- .../control}/model/embeddings_list.py | 10 +- .../control}/model/embeddings_list_usage.py | 6 +- .../control}/model/index_list.py | 8 +- .../control}/model/index_model.py | 10 +- .../control}/model/index_model_spec.py | 10 +- .../control}/model/index_model_status.py | 6 +- .../control}/model/index_spec.py | 10 +- .../control}/model/inline_response401.py | 8 +- .../model/inline_response401_error.py | 6 +- .../control}/model/pod_spec.py | 8 +- .../model/pod_spec_metadata_config.py | 6 +- .../control}/model/serverless_spec.py | 6 +- .../core/openapi/control/models/__init__.py | 34 ++++ pinecone/core/openapi/data/__init__.py | 28 ++++ .../client => openapi/data}/api/__init__.py | 2 +- .../data}/api/data_plane_api.py | 26 +-- .../client => openapi/data}/apis/__init__.py | 2 +- .../client => openapi/data}/model/__init__.py | 0 .../data}/model/delete_request.py | 6 +- .../model/describe_index_stats_request.py | 6 +- .../model/describe_index_stats_response.py | 8 +- .../data}/model/fetch_response.py | 10 +- .../data}/model/list_item.py | 6 +- .../data}/model/list_response.py | 12 +- .../data}/model/namespace_summary.py | 6 +- .../data}/model/pagination.py | 6 +- .../data}/model/protobuf_any.py | 6 +- .../data}/model/protobuf_null_value.py | 6 +- .../data}/model/query_request.py | 10 +- .../data}/model/query_response.py | 12 +- .../data}/model/query_vector.py | 8 +- .../data}/model/rpc_status.py | 8 +- .../data}/model/scored_vector.py | 8 +- .../data}/model/single_query_results.py | 8 +- .../data}/model/sparse_values.py | 6 +- .../data}/model/update_request.py | 8 +- .../data}/model/upsert_request.py | 8 +- .../data}/model/upsert_response.py | 6 +- .../client => openapi/data}/model/usage.py | 6 +- .../client => openapi/data}/model/vector.py | 8 +- pinecone/core/openapi/data/models/__init__.py | 33 ++++ .../core/{ => openapi}/shared/api_client.py | 8 +- .../{ => openapi}/shared/configuration.py | 6 +- .../core/{ => openapi}/shared/exceptions.py | 0 .../core/{ => openapi}/shared/model_utils.py | 2 +- pinecone/core/{ => openapi}/shared/rest.py | 2 +- pinecone/data/index.py | 8 +- pinecone/data/sparse_vector_factory.py | 2 +- pinecone/data/vector_factory.py | 2 +- pinecone/exceptions/__init__.py | 2 +- pinecone/exceptions/exceptions.py | 2 +- pinecone/exceptions/openapi_exceptions.py | 150 ++++++++++++++++++ pinecone/grpc/index_grpc.py | 2 +- pinecone/grpc/utils.py | 2 +- pinecone/models/collection_list.py | 2 +- pinecone/models/index_list.py | 2 +- .../data/test_openapi_configuration.py | 2 +- tests/unit/models/test_collection_list.py | 2 +- tests/unit/models/test_index_list.py | 2 +- tests/unit/test_config.py | 2 +- tests/unit/test_config_builder.py | 2 +- tests/unit/test_control.py | 6 +- tests/unit/utils/test_setup_openapi_client.py | 4 +- 94 files changed, 529 insertions(+), 376 deletions(-) delete mode 100644 pinecone/core/control/__init__.py delete mode 100644 pinecone/core/control/client/__init__.py delete mode 100644 pinecone/core/control/client/models/__init__.py delete mode 100644 pinecone/core/data/__init__.py delete mode 100644 pinecone/core/data/client/__init__.py delete mode 100644 pinecone/core/data/client/models/__init__.py create mode 100644 pinecone/core/openapi/control/__init__.py rename pinecone/core/{control/client => openapi/control}/api/__init__.py (73%) rename pinecone/core/{control/client => openapi/control}/api/inference_api.py (91%) rename pinecone/core/{control/client => openapi/control}/api/manage_indexes_api.py (97%) rename pinecone/core/{control/client => openapi/control}/apis/__init__.py (72%) rename pinecone/core/{control/client => openapi/control}/model/__init__.py (100%) rename pinecone/core/{control/client => openapi/control}/model/collection_list.py (97%) rename pinecone/core/{control/client => openapi/control}/model/collection_model.py (98%) rename pinecone/core/{control/client => openapi/control}/model/configure_index_request.py (97%) rename pinecone/core/{control/client => openapi/control}/model/configure_index_request_spec.py (97%) rename pinecone/core/{control/client => openapi/control}/model/configure_index_request_spec_pod.py (98%) rename pinecone/core/{control/client => openapi/control}/model/create_collection_request.py (98%) rename pinecone/core/{control/client => openapi/control}/model/create_index_request.py (97%) rename pinecone/core/{control/client => openapi/control}/model/embed_request.py (96%) rename pinecone/core/{control/client => openapi/control}/model/embed_request_inputs.py (98%) rename pinecone/core/{control/client => openapi/control}/model/embed_request_parameters.py (98%) rename pinecone/core/{control/client => openapi/control}/model/embedding.py (98%) rename pinecone/core/{control/client => openapi/control}/model/embeddings_list.py (96%) rename pinecone/core/{control/client => openapi/control}/model/embeddings_list_usage.py (98%) rename pinecone/core/{control/client => openapi/control}/model/index_list.py (97%) rename pinecone/core/{control/client => openapi/control}/model/index_model.py (97%) rename pinecone/core/{control/client => openapi/control}/model/index_model_spec.py (96%) rename pinecone/core/{control/client => openapi/control}/model/index_model_status.py (98%) rename pinecone/core/{control/client => openapi/control}/model/index_spec.py (96%) rename pinecone/core/{control/client => openapi/control}/model/inline_response401.py (97%) rename pinecone/core/{control/client => openapi/control}/model/inline_response401_error.py (98%) rename pinecone/core/{control/client => openapi/control}/model/pod_spec.py (97%) rename pinecone/core/{control/client => openapi/control}/model/pod_spec_metadata_config.py (98%) rename pinecone/core/{control/client => openapi/control}/model/serverless_spec.py (98%) create mode 100644 pinecone/core/openapi/control/models/__init__.py create mode 100644 pinecone/core/openapi/data/__init__.py rename pinecone/core/{data/client => openapi/data}/api/__init__.py (74%) rename pinecone/core/{data/client => openapi/data}/api/data_plane_api.py (97%) rename pinecone/core/{data/client => openapi/data}/apis/__init__.py (85%) rename pinecone/core/{data/client => openapi/data}/model/__init__.py (100%) rename pinecone/core/{data/client => openapi/data}/model/delete_request.py (98%) rename pinecone/core/{data/client => openapi/data}/model/describe_index_stats_request.py (98%) rename pinecone/core/{data/client => openapi/data}/model/describe_index_stats_response.py (97%) rename pinecone/core/{data/client => openapi/data}/model/fetch_response.py (97%) rename pinecone/core/{data/client => openapi/data}/model/list_item.py (98%) rename pinecone/core/{data/client => openapi/data}/model/list_response.py (96%) rename pinecone/core/{data/client => openapi/data}/model/namespace_summary.py (98%) rename pinecone/core/{data/client => openapi/data}/model/pagination.py (98%) rename pinecone/core/{data/client => openapi/data}/model/protobuf_any.py (98%) rename pinecone/core/{data/client => openapi/data}/model/protobuf_null_value.py (98%) rename pinecone/core/{data/client => openapi/data}/model/query_request.py (97%) rename pinecone/core/{data/client => openapi/data}/model/query_response.py (96%) rename pinecone/core/{data/client => openapi/data}/model/query_vector.py (97%) rename pinecone/core/{data/client => openapi/data}/model/rpc_status.py (97%) rename pinecone/core/{data/client => openapi/data}/model/scored_vector.py (97%) rename pinecone/core/{data/client => openapi/data}/model/single_query_results.py (97%) rename pinecone/core/{data/client => openapi/data}/model/sparse_values.py (98%) rename pinecone/core/{data/client => openapi/data}/model/update_request.py (97%) rename pinecone/core/{data/client => openapi/data}/model/upsert_request.py (97%) rename pinecone/core/{data/client => openapi/data}/model/upsert_response.py (98%) rename pinecone/core/{data/client => openapi/data}/model/usage.py (98%) rename pinecone/core/{data/client => openapi/data}/model/vector.py (97%) create mode 100644 pinecone/core/openapi/data/models/__init__.py rename pinecone/core/{ => openapi}/shared/api_client.py (99%) rename pinecone/core/{ => openapi}/shared/configuration.py (99%) rename pinecone/core/{ => openapi}/shared/exceptions.py (100%) rename pinecone/core/{ => openapi}/shared/model_utils.py (99%) rename pinecone/core/{ => openapi}/shared/rest.py (99%) create mode 100644 pinecone/exceptions/openapi_exceptions.py diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index ea2772bbf..d4af30efd 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -5,7 +5,7 @@ set -eux -o pipefail version='2024-07' modules=("control" "data") -destination="pinecone/core" +destination="pinecone/core/openapi" rm -rf build mkdir build @@ -71,13 +71,12 @@ generate_client() { # Copy the generated module to the correct location rm -rf "${destination}/${module_name}" - cp -r "build/pinecone/core/${module_name}" "${destination}/${module_name}" + cp -r "build/pinecone/core/openapi/${module_name}" "${destination}/${module_name}" } extract_shared_classes() { target_directory="${destination}/shared" - rm -rf $target_directory - mkdir -p $target_directory + mkdir -p "$target_directory" # Define the list of shared source files sharedFiles=( @@ -88,7 +87,7 @@ extract_shared_classes() { "rest" ) - source_directory="${destination}/${modules[0]}/client" + source_directory="${destination}/${modules[0]}" # Loop through each file we want to share and copy it to the target directory for file in "${sharedFiles[@]}"; do @@ -97,7 +96,7 @@ extract_shared_classes() { # Cleanup shared files in each module for module in "${modules[@]}"; do - source_directory="${destination}/${module}/client" + source_directory="${destination}/${module}" for file in "${sharedFiles[@]}"; do rm "${source_directory}/${file}.py" done @@ -111,12 +110,13 @@ extract_shared_classes() { # Adjust import paths in every file find "${destination}" -name "*.py" | while IFS= read -r file; do - sed -i '' 's/from \.\.model_utils/from pinecone\.core\.shared\.model_utils/g' "$file" - sed -i '' 's/from pinecone\.core\.control\.client import rest/from pinecone\.core\.shared import rest/g' "$file" + sed -i '' 's/from \.\.model_utils/from pinecone\.core\.openapi\.shared\.model_utils/g' "$file" for module in "${modules[@]}"; do + sed -i '' "s/from pinecone\.core\.openapi\.$module import rest/from pinecone\.core\.openapi\.shared import rest/g" "$file" + for sharedFile in "${sharedFiles[@]}"; do - sed -i '' "s/from pinecone\.core\.$module\.client\.$sharedFile/from pinecone\.core\.shared\.$sharedFile/g" "$file" + sed -i '' "s/from pinecone\.core\.openapi\.$module\.$sharedFile/from pinecone\.core\.openapi\.shared\.$sharedFile/g" "$file" done done done @@ -125,6 +125,9 @@ extract_shared_classes() { update_apis_repo verify_spec_version $version +rm -rf "${destination}" +mkdir -p "${destination}" + for module in "${modules[@]}"; do generate_client $module done diff --git a/codegen/openapi-config.control.json b/codegen/openapi-config.control.json index c07f29519..487ddfca4 100644 --- a/codegen/openapi-config.control.json +++ b/codegen/openapi-config.control.json @@ -1,4 +1,4 @@ { - "packageName": "pinecone.core.control.client", + "packageName": "pinecone.core.openapi.control", "pythonAttrNoneIfUnset": true } \ No newline at end of file diff --git a/codegen/openapi-config.data.json b/codegen/openapi-config.data.json index daf1314ec..f6db8659c 100644 --- a/codegen/openapi-config.data.json +++ b/codegen/openapi-config.data.json @@ -1,4 +1,4 @@ { - "packageName": "pinecone.core.data.client", + "packageName": "pinecone.core.openapi.data", "pythonAttrNoneIfUnset": true } \ No newline at end of file diff --git a/pinecone/__init__.py b/pinecone/__init__.py index e997a74a1..46d7fc186 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -14,7 +14,7 @@ from .data import * from .models import * -from .core.control.client.models import ( +from .core.openapi.control.models import ( IndexModel, ) diff --git a/pinecone/config/config.py b/pinecone/config/config.py index 7546d3d0e..2180d3e5e 100644 --- a/pinecone/config/config.py +++ b/pinecone/config/config.py @@ -3,7 +3,7 @@ from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config.openapi import OpenApiConfigFactory -from pinecone.core.shared.configuration import ( +from pinecone.core.openapi.shared.configuration import ( Configuration as OpenApiConfiguration, ) from pinecone.utils import normalize_host diff --git a/pinecone/config/openapi.py b/pinecone/config/openapi.py index b12d438d6..05d1d37bf 100644 --- a/pinecone/config/openapi.py +++ b/pinecone/config/openapi.py @@ -7,7 +7,7 @@ from urllib3.connection import HTTPConnection -from pinecone.core.shared.configuration import ( +from pinecone.core.openapi.shared.configuration import ( Configuration as OpenApiConfiguration, ) diff --git a/pinecone/control/index_host_store.py b/pinecone/control/index_host_store.py index ea6c3510e..26efd4fa0 100644 --- a/pinecone/control/index_host_store.py +++ b/pinecone/control/index_host_store.py @@ -1,9 +1,9 @@ from typing import Dict from pinecone.config import Config -from pinecone.core.control.client.api.manage_indexes_api import ( +from pinecone.core.openapi.control.api.manage_indexes_api import ( ManageIndexesApi as IndexOperationsApi, ) -from pinecone.core.shared.exceptions import PineconeException +from pinecone.core.openapi.shared.exceptions import PineconeException from pinecone.utils import normalize_host diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index eec971c78..4d75f5b9d 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -7,17 +7,17 @@ from pinecone.config import PineconeConfig, Config, ConfigBuilder -from pinecone.core.control.client.api.manage_indexes_api import ( +from pinecone.core.openapi.control.api.manage_indexes_api import ( ManageIndexesApi, ) -from pinecone.core.shared.api_client import ApiClient +from pinecone.core.openapi.shared.api_client import ApiClient from pinecone.utils import ( normalize_host, setup_openapi_client, build_plugin_setup_client, ) -from pinecone.core.control.client.models import ( +from pinecone.core.openapi.control.models import ( CreateCollectionRequest, CreateIndexRequest, ConfigureIndexRequest, diff --git a/pinecone/core/control/__init__.py b/pinecone/core/control/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/core/control/client/__init__.py b/pinecone/core/control/client/__init__.py deleted file mode 100644 index 0e28e94db..000000000 --- a/pinecone/core/control/client/__init__.py +++ /dev/null @@ -1,28 +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 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.core.shared.api_client import ApiClient - -# import Configuration -from pinecone.core.shared.configuration import Configuration - -# import exceptions -from pinecone.core.shared.exceptions import PineconeException -from pinecone.core.shared.exceptions import PineconeApiAttributeError -from pinecone.core.shared.exceptions import PineconeApiTypeError -from pinecone.core.shared.exceptions import PineconeApiValueError -from pinecone.core.shared.exceptions import PineconeApiKeyError -from pinecone.core.shared.exceptions import PineconeApiException diff --git a/pinecone/core/control/client/models/__init__.py b/pinecone/core/control/client/models/__init__.py deleted file mode 100644 index a6400a47a..000000000 --- a/pinecone/core/control/client/models/__init__.py +++ /dev/null @@ -1,34 +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.control.client.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.control.client.model.collection_list import CollectionList -from pinecone.core.control.client.model.collection_model import CollectionModel -from pinecone.core.control.client.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.control.client.model.configure_index_request_spec import ConfigureIndexRequestSpec -from pinecone.core.control.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod -from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.control.client.model.create_index_request import CreateIndexRequest -from pinecone.core.control.client.model.embed_request import EmbedRequest -from pinecone.core.control.client.model.embed_request_inputs import EmbedRequestInputs -from pinecone.core.control.client.model.embed_request_parameters import EmbedRequestParameters -from pinecone.core.control.client.model.embedding import Embedding -from pinecone.core.control.client.model.embeddings_list import EmbeddingsList -from pinecone.core.control.client.model.embeddings_list_usage import EmbeddingsListUsage -from pinecone.core.control.client.model.index_list import IndexList -from pinecone.core.control.client.model.index_model import IndexModel -from pinecone.core.control.client.model.index_model_spec import IndexModelSpec -from pinecone.core.control.client.model.index_model_status import IndexModelStatus -from pinecone.core.control.client.model.index_spec import IndexSpec -from pinecone.core.control.client.model.inline_response401 import InlineResponse401 -from pinecone.core.control.client.model.inline_response401_error import InlineResponse401Error -from pinecone.core.control.client.model.pod_spec import PodSpec -from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig -from pinecone.core.control.client.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/data/__init__.py b/pinecone/core/data/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pinecone/core/data/client/__init__.py b/pinecone/core/data/client/__init__.py deleted file mode 100644 index 4251eb3c3..000000000 --- a/pinecone/core/data/client/__init__.py +++ /dev/null @@ -1,28 +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 - - The version of the OpenAPI document: 2024-07 - Contact: support@pinecone.io - Generated by: https://openapi-generator.tech -""" - - -__version__ = "1.0.0" - -# import ApiClient -from pinecone.core.shared.api_client import ApiClient - -# import Configuration -from pinecone.core.shared.configuration import Configuration - -# import exceptions -from pinecone.core.shared.exceptions import PineconeException -from pinecone.core.shared.exceptions import PineconeApiAttributeError -from pinecone.core.shared.exceptions import PineconeApiTypeError -from pinecone.core.shared.exceptions import PineconeApiValueError -from pinecone.core.shared.exceptions import PineconeApiKeyError -from pinecone.core.shared.exceptions import PineconeApiException diff --git a/pinecone/core/data/client/models/__init__.py b/pinecone/core/data/client/models/__init__.py deleted file mode 100644 index 459eddd4e..000000000 --- a/pinecone/core/data/client/models/__init__.py +++ /dev/null @@ -1,33 +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.data.client.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from pinecone.core.data.client.model.delete_request import DeleteRequest -from pinecone.core.data.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.data.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.data.client.model.fetch_response import FetchResponse -from pinecone.core.data.client.model.list_item import ListItem -from pinecone.core.data.client.model.list_response import ListResponse -from pinecone.core.data.client.model.namespace_summary import NamespaceSummary -from pinecone.core.data.client.model.pagination import Pagination -from pinecone.core.data.client.model.protobuf_any import ProtobufAny -from pinecone.core.data.client.model.protobuf_null_value import ProtobufNullValue -from pinecone.core.data.client.model.query_request import QueryRequest -from pinecone.core.data.client.model.query_response import QueryResponse -from pinecone.core.data.client.model.query_vector import QueryVector -from pinecone.core.data.client.model.rpc_status import RpcStatus -from pinecone.core.data.client.model.scored_vector import ScoredVector -from pinecone.core.data.client.model.single_query_results import SingleQueryResults -from pinecone.core.data.client.model.sparse_values import SparseValues -from pinecone.core.data.client.model.update_request import UpdateRequest -from pinecone.core.data.client.model.upsert_request import UpsertRequest -from pinecone.core.data.client.model.upsert_response import UpsertResponse -from pinecone.core.data.client.model.usage import Usage -from pinecone.core.data.client.model.vector import Vector diff --git a/pinecone/core/openapi/control/__init__.py b/pinecone/core/openapi/control/__init__.py new file mode 100644 index 000000000..413b28722 --- /dev/null +++ b/pinecone/core/openapi/control/__init__.py @@ -0,0 +1,28 @@ +# 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 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from pinecone.core.openapi.shared.api_client import ApiClient + +# import Configuration +from pinecone.core.openapi.shared.configuration import Configuration + +# import exceptions +from pinecone.core.openapi.shared.exceptions import PineconeException +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.exceptions import PineconeApiTypeError +from pinecone.core.openapi.shared.exceptions import PineconeApiValueError +from pinecone.core.openapi.shared.exceptions import PineconeApiKeyError +from pinecone.core.openapi.shared.exceptions import PineconeApiException diff --git a/pinecone/core/control/client/api/__init__.py b/pinecone/core/openapi/control/api/__init__.py similarity index 73% rename from pinecone/core/control/client/api/__init__.py rename to pinecone/core/openapi/control/api/__init__.py index a4a23bd49..7bcc29924 100644 --- a/pinecone/core/control/client/api/__init__.py +++ b/pinecone/core/openapi/control/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.control.client.apis import InferenceApi +# from pinecone.core.openapi.control.apis import InferenceApi diff --git a/pinecone/core/control/client/api/inference_api.py b/pinecone/core/openapi/control/api/inference_api.py similarity index 91% rename from pinecone/core/control/client/api/inference_api.py rename to pinecone/core/openapi/control/api/inference_api.py index adc95ac69..6a14ef748 100644 --- a/pinecone/core/control/client/api/inference_api.py +++ b/pinecone/core/openapi/control/api/inference_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, @@ -21,9 +21,9 @@ none_type, validate_and_convert_types, ) -from pinecone.core.control.client.model.embed_request import EmbedRequest -from pinecone.core.control.client.model.embeddings_list import EmbeddingsList -from pinecone.core.control.client.model.inline_response401 import InlineResponse401 +from pinecone.core.openapi.control.model.embed_request import EmbedRequest +from pinecone.core.openapi.control.model.embeddings_list import EmbeddingsList +from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 class InferenceApi(object): diff --git a/pinecone/core/control/client/api/manage_indexes_api.py b/pinecone/core/openapi/control/api/manage_indexes_api.py similarity index 97% rename from pinecone/core/control/client/api/manage_indexes_api.py rename to pinecone/core/openapi/control/api/manage_indexes_api.py index e560b7feb..b1b9b512f 100644 --- a/pinecone/core/control/client/api/manage_indexes_api.py +++ b/pinecone/core/openapi/control/api/manage_indexes_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, @@ -21,14 +21,14 @@ none_type, validate_and_convert_types, ) -from pinecone.core.control.client.model.collection_list import CollectionList -from pinecone.core.control.client.model.collection_model import CollectionModel -from pinecone.core.control.client.model.configure_index_request import ConfigureIndexRequest -from pinecone.core.control.client.model.create_collection_request import CreateCollectionRequest -from pinecone.core.control.client.model.create_index_request import CreateIndexRequest -from pinecone.core.control.client.model.index_list import IndexList -from pinecone.core.control.client.model.index_model import IndexModel -from pinecone.core.control.client.model.inline_response401 import InlineResponse401 +from pinecone.core.openapi.control.model.collection_list import CollectionList +from pinecone.core.openapi.control.model.collection_model import CollectionModel +from pinecone.core.openapi.control.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.openapi.control.model.create_collection_request import CreateCollectionRequest +from pinecone.core.openapi.control.model.create_index_request import CreateIndexRequest +from pinecone.core.openapi.control.model.index_list import IndexList +from pinecone.core.openapi.control.model.index_model import IndexModel +from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 class ManageIndexesApi(object): diff --git a/pinecone/core/control/client/apis/__init__.py b/pinecone/core/openapi/control/apis/__init__.py similarity index 72% rename from pinecone/core/control/client/apis/__init__.py rename to pinecone/core/openapi/control/apis/__init__.py index d0d2a0a9f..ee6d6a50d 100644 --- a/pinecone/core/control/client/apis/__init__.py +++ b/pinecone/core/openapi/control/apis/__init__.py @@ -13,5 +13,5 @@ # sys.setrecursionlimit(n) # Import APIs into API package: -from pinecone.core.control.client.api.inference_api import InferenceApi -from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.openapi.control.api.inference_api import InferenceApi +from pinecone.core.openapi.control.api.manage_indexes_api import ManageIndexesApi diff --git a/pinecone/core/control/client/model/__init__.py b/pinecone/core/openapi/control/model/__init__.py similarity index 100% rename from pinecone/core/control/client/model/__init__.py rename to pinecone/core/openapi/control/model/__init__.py diff --git a/pinecone/core/control/client/model/collection_list.py b/pinecone/core/openapi/control/model/collection_list.py similarity index 97% rename from pinecone/core/control/client/model/collection_list.py rename to pinecone/core/openapi/control/model/collection_list.py index 726b20b8f..637f85c8a 100644 --- a/pinecone/core/control/client/model/collection_list.py +++ b/pinecone/core/openapi/control/model/collection_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.collection_model import CollectionModel + from pinecone.core.openapi.control.model.collection_model import CollectionModel globals()["CollectionModel"] = CollectionModel diff --git a/pinecone/core/control/client/model/collection_model.py b/pinecone/core/openapi/control/model/collection_model.py similarity index 98% rename from pinecone/core/control/client/model/collection_model.py rename to pinecone/core/openapi/control/model/collection_model.py index 4b4184c85..a0779fe9b 100644 --- a/pinecone/core/control/client/model/collection_model.py +++ b/pinecone/core/openapi/control/model/collection_model.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class CollectionModel(ModelNormal): diff --git a/pinecone/core/control/client/model/configure_index_request.py b/pinecone/core/openapi/control/model/configure_index_request.py similarity index 97% rename from pinecone/core/control/client/model/configure_index_request.py rename to pinecone/core/openapi/control/model/configure_index_request.py index 0745cb299..265a3ccc8 100644 --- a/pinecone/core/control/client/model/configure_index_request.py +++ b/pinecone/core/openapi/control/model/configure_index_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.configure_index_request_spec import ConfigureIndexRequestSpec + from pinecone.core.openapi.control.model.configure_index_request_spec import ConfigureIndexRequestSpec globals()["ConfigureIndexRequestSpec"] = ConfigureIndexRequestSpec diff --git a/pinecone/core/control/client/model/configure_index_request_spec.py b/pinecone/core/openapi/control/model/configure_index_request_spec.py similarity index 97% rename from pinecone/core/control/client/model/configure_index_request_spec.py rename to pinecone/core/openapi/control/model/configure_index_request_spec.py index 74a22d06f..2de42f1fb 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec.py +++ b/pinecone/core/openapi/control/model/configure_index_request_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod + from pinecone.core.openapi.control.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod globals()["ConfigureIndexRequestSpecPod"] = ConfigureIndexRequestSpecPod diff --git a/pinecone/core/control/client/model/configure_index_request_spec_pod.py b/pinecone/core/openapi/control/model/configure_index_request_spec_pod.py similarity index 98% rename from pinecone/core/control/client/model/configure_index_request_spec_pod.py rename to pinecone/core/openapi/control/model/configure_index_request_spec_pod.py index e3b5ca1d7..b10ceb166 100644 --- a/pinecone/core/control/client/model/configure_index_request_spec_pod.py +++ b/pinecone/core/openapi/control/model/configure_index_request_spec_pod.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class ConfigureIndexRequestSpecPod(ModelNormal): diff --git a/pinecone/core/control/client/model/create_collection_request.py b/pinecone/core/openapi/control/model/create_collection_request.py similarity index 98% rename from pinecone/core/control/client/model/create_collection_request.py rename to pinecone/core/openapi/control/model/create_collection_request.py index a6cd13bb7..9d00ae59c 100644 --- a/pinecone/core/control/client/model/create_collection_request.py +++ b/pinecone/core/openapi/control/model/create_collection_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class CreateCollectionRequest(ModelNormal): diff --git a/pinecone/core/control/client/model/create_index_request.py b/pinecone/core/openapi/control/model/create_index_request.py similarity index 97% rename from pinecone/core/control/client/model/create_index_request.py rename to pinecone/core/openapi/control/model/create_index_request.py index f0e4d3826..4e21d13fa 100644 --- a/pinecone/core/control/client/model/create_index_request.py +++ b/pinecone/core/openapi/control/model/create_index_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.index_spec import IndexSpec + from pinecone.core.openapi.control.model.index_spec import IndexSpec globals()["IndexSpec"] = IndexSpec diff --git a/pinecone/core/control/client/model/embed_request.py b/pinecone/core/openapi/control/model/embed_request.py similarity index 96% rename from pinecone/core/control/client/model/embed_request.py rename to pinecone/core/openapi/control/model/embed_request.py index e577c172b..39bff5194 100644 --- a/pinecone/core/control/client/model/embed_request.py +++ b/pinecone/core/openapi/control/model/embed_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.embed_request_inputs import EmbedRequestInputs - from pinecone.core.control.client.model.embed_request_parameters import EmbedRequestParameters + from pinecone.core.openapi.control.model.embed_request_inputs import EmbedRequestInputs + from pinecone.core.openapi.control.model.embed_request_parameters import EmbedRequestParameters globals()["EmbedRequestInputs"] = EmbedRequestInputs globals()["EmbedRequestParameters"] = EmbedRequestParameters diff --git a/pinecone/core/control/client/model/embed_request_inputs.py b/pinecone/core/openapi/control/model/embed_request_inputs.py similarity index 98% rename from pinecone/core/control/client/model/embed_request_inputs.py rename to pinecone/core/openapi/control/model/embed_request_inputs.py index 08edc3d7a..0726bf9d3 100644 --- a/pinecone/core/control/client/model/embed_request_inputs.py +++ b/pinecone/core/openapi/control/model/embed_request_inputs.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class EmbedRequestInputs(ModelNormal): diff --git a/pinecone/core/control/client/model/embed_request_parameters.py b/pinecone/core/openapi/control/model/embed_request_parameters.py similarity index 98% rename from pinecone/core/control/client/model/embed_request_parameters.py rename to pinecone/core/openapi/control/model/embed_request_parameters.py index ff9f8b0a6..4c6597b0b 100644 --- a/pinecone/core/control/client/model/embed_request_parameters.py +++ b/pinecone/core/openapi/control/model/embed_request_parameters.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class EmbedRequestParameters(ModelNormal): diff --git a/pinecone/core/control/client/model/embedding.py b/pinecone/core/openapi/control/model/embedding.py similarity index 98% rename from pinecone/core/control/client/model/embedding.py rename to pinecone/core/openapi/control/model/embedding.py index c97ba2e4f..58b4caf9c 100644 --- a/pinecone/core/control/client/model/embedding.py +++ b/pinecone/core/openapi/control/model/embedding.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class Embedding(ModelNormal): diff --git a/pinecone/core/control/client/model/embeddings_list.py b/pinecone/core/openapi/control/model/embeddings_list.py similarity index 96% rename from pinecone/core/control/client/model/embeddings_list.py rename to pinecone/core/openapi/control/model/embeddings_list.py index 6d2f70ebb..a95209b70 100644 --- a/pinecone/core/control/client/model/embeddings_list.py +++ b/pinecone/core/openapi/control/model/embeddings_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.embedding import Embedding - from pinecone.core.control.client.model.embeddings_list_usage import EmbeddingsListUsage + from pinecone.core.openapi.control.model.embedding import Embedding + from pinecone.core.openapi.control.model.embeddings_list_usage import EmbeddingsListUsage globals()["Embedding"] = Embedding globals()["EmbeddingsListUsage"] = EmbeddingsListUsage diff --git a/pinecone/core/control/client/model/embeddings_list_usage.py b/pinecone/core/openapi/control/model/embeddings_list_usage.py similarity index 98% rename from pinecone/core/control/client/model/embeddings_list_usage.py rename to pinecone/core/openapi/control/model/embeddings_list_usage.py index 32ea91ec4..c6a570d12 100644 --- a/pinecone/core/control/client/model/embeddings_list_usage.py +++ b/pinecone/core/openapi/control/model/embeddings_list_usage.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class EmbeddingsListUsage(ModelNormal): diff --git a/pinecone/core/control/client/model/index_list.py b/pinecone/core/openapi/control/model/index_list.py similarity index 97% rename from pinecone/core/control/client/model/index_list.py rename to pinecone/core/openapi/control/model/index_list.py index fcd23bb26..fdde039e6 100644 --- a/pinecone/core/control/client/model/index_list.py +++ b/pinecone/core/openapi/control/model/index_list.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.index_model import IndexModel + from pinecone.core.openapi.control.model.index_model import IndexModel globals()["IndexModel"] = IndexModel diff --git a/pinecone/core/control/client/model/index_model.py b/pinecone/core/openapi/control/model/index_model.py similarity index 97% rename from pinecone/core/control/client/model/index_model.py rename to pinecone/core/openapi/control/model/index_model.py index c80080d7a..60fe4ef3f 100644 --- a/pinecone/core/control/client/model/index_model.py +++ b/pinecone/core/openapi/control/model/index_model.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.index_model_spec import IndexModelSpec - from pinecone.core.control.client.model.index_model_status import IndexModelStatus + from pinecone.core.openapi.control.model.index_model_spec import IndexModelSpec + from pinecone.core.openapi.control.model.index_model_status import IndexModelStatus globals()["IndexModelSpec"] = IndexModelSpec globals()["IndexModelStatus"] = IndexModelStatus diff --git a/pinecone/core/control/client/model/index_model_spec.py b/pinecone/core/openapi/control/model/index_model_spec.py similarity index 96% rename from pinecone/core/control/client/model/index_model_spec.py rename to pinecone/core/openapi/control/model/index_model_spec.py index e4ef37804..5202f1fc8 100644 --- a/pinecone/core/control/client/model/index_model_spec.py +++ b/pinecone/core/openapi/control/model/index_model_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.pod_spec import PodSpec - from pinecone.core.control.client.model.serverless_spec import ServerlessSpec + from pinecone.core.openapi.control.model.pod_spec import PodSpec + from pinecone.core.openapi.control.model.serverless_spec import ServerlessSpec globals()["PodSpec"] = PodSpec globals()["ServerlessSpec"] = ServerlessSpec diff --git a/pinecone/core/control/client/model/index_model_status.py b/pinecone/core/openapi/control/model/index_model_status.py similarity index 98% rename from pinecone/core/control/client/model/index_model_status.py rename to pinecone/core/openapi/control/model/index_model_status.py index fa1a484ed..555362efd 100644 --- a/pinecone/core/control/client/model/index_model_status.py +++ b/pinecone/core/openapi/control/model/index_model_status.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class IndexModelStatus(ModelNormal): diff --git a/pinecone/core/control/client/model/index_spec.py b/pinecone/core/openapi/control/model/index_spec.py similarity index 96% rename from pinecone/core/control/client/model/index_spec.py rename to pinecone/core/openapi/control/model/index_spec.py index acc1e01a1..195daedcc 100644 --- a/pinecone/core/control/client/model/index_spec.py +++ b/pinecone/core/openapi/control/model/index_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.pod_spec import PodSpec - from pinecone.core.control.client.model.serverless_spec import ServerlessSpec + from pinecone.core.openapi.control.model.pod_spec import PodSpec + from pinecone.core.openapi.control.model.serverless_spec import ServerlessSpec globals()["PodSpec"] = PodSpec globals()["ServerlessSpec"] = ServerlessSpec diff --git a/pinecone/core/control/client/model/inline_response401.py b/pinecone/core/openapi/control/model/inline_response401.py similarity index 97% rename from pinecone/core/control/client/model/inline_response401.py rename to pinecone/core/openapi/control/model/inline_response401.py index f98753c7c..5d8618bfc 100644 --- a/pinecone/core/control/client/model/inline_response401.py +++ b/pinecone/core/openapi/control/model/inline_response401.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.inline_response401_error import InlineResponse401Error + from pinecone.core.openapi.control.model.inline_response401_error import InlineResponse401Error globals()["InlineResponse401Error"] = InlineResponse401Error diff --git a/pinecone/core/control/client/model/inline_response401_error.py b/pinecone/core/openapi/control/model/inline_response401_error.py similarity index 98% rename from pinecone/core/control/client/model/inline_response401_error.py rename to pinecone/core/openapi/control/model/inline_response401_error.py index 9d3819029..33774f42c 100644 --- a/pinecone/core/control/client/model/inline_response401_error.py +++ b/pinecone/core/openapi/control/model/inline_response401_error.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class InlineResponse401Error(ModelNormal): diff --git a/pinecone/core/control/client/model/pod_spec.py b/pinecone/core/openapi/control/model/pod_spec.py similarity index 97% rename from pinecone/core/control/client/model/pod_spec.py rename to pinecone/core/openapi/control/model/pod_spec.py index 63009568e..a20e22b13 100644 --- a/pinecone/core/control/client/model/pod_spec.py +++ b/pinecone/core/openapi/control/model/pod_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.control.client.model.pod_spec_metadata_config import PodSpecMetadataConfig + from pinecone.core.openapi.control.model.pod_spec_metadata_config import PodSpecMetadataConfig globals()["PodSpecMetadataConfig"] = PodSpecMetadataConfig diff --git a/pinecone/core/control/client/model/pod_spec_metadata_config.py b/pinecone/core/openapi/control/model/pod_spec_metadata_config.py similarity index 98% rename from pinecone/core/control/client/model/pod_spec_metadata_config.py rename to pinecone/core/openapi/control/model/pod_spec_metadata_config.py index f2d4200dd..05b016202 100644 --- a/pinecone/core/control/client/model/pod_spec_metadata_config.py +++ b/pinecone/core/openapi/control/model/pod_spec_metadata_config.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class PodSpecMetadataConfig(ModelNormal): diff --git a/pinecone/core/control/client/model/serverless_spec.py b/pinecone/core/openapi/control/model/serverless_spec.py similarity index 98% rename from pinecone/core/control/client/model/serverless_spec.py rename to pinecone/core/openapi/control/model/serverless_spec.py index bad5b35bd..2af0d1369 100644 --- a/pinecone/core/control/client/model/serverless_spec.py +++ b/pinecone/core/openapi/control/model/serverless_spec.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class ServerlessSpec(ModelNormal): diff --git a/pinecone/core/openapi/control/models/__init__.py b/pinecone/core/openapi/control/models/__init__.py new file mode 100644 index 000000000..29a7c69bf --- /dev/null +++ b/pinecone/core/openapi/control/models/__init__.py @@ -0,0 +1,34 @@ +# 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.control.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from pinecone.core.openapi.control.model.collection_list import CollectionList +from pinecone.core.openapi.control.model.collection_model import CollectionModel +from pinecone.core.openapi.control.model.configure_index_request import ConfigureIndexRequest +from pinecone.core.openapi.control.model.configure_index_request_spec import ConfigureIndexRequestSpec +from pinecone.core.openapi.control.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod +from pinecone.core.openapi.control.model.create_collection_request import CreateCollectionRequest +from pinecone.core.openapi.control.model.create_index_request import CreateIndexRequest +from pinecone.core.openapi.control.model.embed_request import EmbedRequest +from pinecone.core.openapi.control.model.embed_request_inputs import EmbedRequestInputs +from pinecone.core.openapi.control.model.embed_request_parameters import EmbedRequestParameters +from pinecone.core.openapi.control.model.embedding import Embedding +from pinecone.core.openapi.control.model.embeddings_list import EmbeddingsList +from pinecone.core.openapi.control.model.embeddings_list_usage import EmbeddingsListUsage +from pinecone.core.openapi.control.model.index_list import IndexList +from pinecone.core.openapi.control.model.index_model import IndexModel +from pinecone.core.openapi.control.model.index_model_spec import IndexModelSpec +from pinecone.core.openapi.control.model.index_model_status import IndexModelStatus +from pinecone.core.openapi.control.model.index_spec import IndexSpec +from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 +from pinecone.core.openapi.control.model.inline_response401_error import InlineResponse401Error +from pinecone.core.openapi.control.model.pod_spec import PodSpec +from pinecone.core.openapi.control.model.pod_spec_metadata_config import PodSpecMetadataConfig +from pinecone.core.openapi.control.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/openapi/data/__init__.py b/pinecone/core/openapi/data/__init__.py new file mode 100644 index 000000000..208c43587 --- /dev/null +++ b/pinecone/core/openapi/data/__init__.py @@ -0,0 +1,28 @@ +# 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 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from pinecone.core.openapi.shared.api_client import ApiClient + +# import Configuration +from pinecone.core.openapi.shared.configuration import Configuration + +# import exceptions +from pinecone.core.openapi.shared.exceptions import PineconeException +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.exceptions import PineconeApiTypeError +from pinecone.core.openapi.shared.exceptions import PineconeApiValueError +from pinecone.core.openapi.shared.exceptions import PineconeApiKeyError +from pinecone.core.openapi.shared.exceptions import PineconeApiException diff --git a/pinecone/core/data/client/api/__init__.py b/pinecone/core/openapi/data/api/__init__.py similarity index 74% rename from pinecone/core/data/client/api/__init__.py rename to pinecone/core/openapi/data/api/__init__.py index f8da73fe3..5f4a45d58 100644 --- a/pinecone/core/data/client/api/__init__.py +++ b/pinecone/core/openapi/data/api/__init__.py @@ -1,3 +1,3 @@ # do not import all apis into this module because that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with -# from pinecone.core.data.client.apis import DataPlaneApi +# from pinecone.core.openapi.data.apis import DataPlaneApi diff --git a/pinecone/core/data/client/api/data_plane_api.py b/pinecone/core/openapi/data/api/data_plane_api.py similarity index 97% rename from pinecone/core/data/client/api/data_plane_api.py rename to pinecone/core/openapi/data/api/data_plane_api.py index eff177296..ab9c36aba 100644 --- a/pinecone/core/data/client/api/data_plane_api.py +++ b/pinecone/core/openapi/data/api/data_plane_api.py @@ -11,8 +11,8 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.api_client import ApiClient, Endpoint as _Endpoint -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.api_client import ApiClient, Endpoint as _Endpoint +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, @@ -21,17 +21,17 @@ none_type, validate_and_convert_types, ) -from pinecone.core.data.client.model.delete_request import DeleteRequest -from pinecone.core.data.client.model.describe_index_stats_request import DescribeIndexStatsRequest -from pinecone.core.data.client.model.describe_index_stats_response import DescribeIndexStatsResponse -from pinecone.core.data.client.model.fetch_response import FetchResponse -from pinecone.core.data.client.model.list_response import ListResponse -from pinecone.core.data.client.model.query_request import QueryRequest -from pinecone.core.data.client.model.query_response import QueryResponse -from pinecone.core.data.client.model.rpc_status import RpcStatus -from pinecone.core.data.client.model.update_request import UpdateRequest -from pinecone.core.data.client.model.upsert_request import UpsertRequest -from pinecone.core.data.client.model.upsert_response import UpsertResponse +from pinecone.core.openapi.data.model.delete_request import DeleteRequest +from pinecone.core.openapi.data.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.openapi.data.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.openapi.data.model.fetch_response import FetchResponse +from pinecone.core.openapi.data.model.list_response import ListResponse +from pinecone.core.openapi.data.model.query_request import QueryRequest +from pinecone.core.openapi.data.model.query_response import QueryResponse +from pinecone.core.openapi.data.model.rpc_status import RpcStatus +from pinecone.core.openapi.data.model.update_request import UpdateRequest +from pinecone.core.openapi.data.model.upsert_request import UpsertRequest +from pinecone.core.openapi.data.model.upsert_response import UpsertResponse class DataPlaneApi(object): diff --git a/pinecone/core/data/client/apis/__init__.py b/pinecone/core/openapi/data/apis/__init__.py similarity index 85% rename from pinecone/core/data/client/apis/__init__.py rename to pinecone/core/openapi/data/apis/__init__.py index d3cf0b6eb..81a897eab 100644 --- a/pinecone/core/data/client/apis/__init__.py +++ b/pinecone/core/openapi/data/apis/__init__.py @@ -13,4 +13,4 @@ # sys.setrecursionlimit(n) # Import APIs into API package: -from pinecone.core.data.client.api.data_plane_api import DataPlaneApi +from pinecone.core.openapi.data.api.data_plane_api import DataPlaneApi diff --git a/pinecone/core/data/client/model/__init__.py b/pinecone/core/openapi/data/model/__init__.py similarity index 100% rename from pinecone/core/data/client/model/__init__.py rename to pinecone/core/openapi/data/model/__init__.py diff --git a/pinecone/core/data/client/model/delete_request.py b/pinecone/core/openapi/data/model/delete_request.py similarity index 98% rename from pinecone/core/data/client/model/delete_request.py rename to pinecone/core/openapi/data/model/delete_request.py index a8d09cbf9..fca6a3d4b 100644 --- a/pinecone/core/data/client/model/delete_request.py +++ b/pinecone/core/openapi/data/model/delete_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class DeleteRequest(ModelNormal): diff --git a/pinecone/core/data/client/model/describe_index_stats_request.py b/pinecone/core/openapi/data/model/describe_index_stats_request.py similarity index 98% rename from pinecone/core/data/client/model/describe_index_stats_request.py rename to pinecone/core/openapi/data/model/describe_index_stats_request.py index 18da99dfb..3f26fe2e9 100644 --- a/pinecone/core/data/client/model/describe_index_stats_request.py +++ b/pinecone/core/openapi/data/model/describe_index_stats_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class DescribeIndexStatsRequest(ModelNormal): diff --git a/pinecone/core/data/client/model/describe_index_stats_response.py b/pinecone/core/openapi/data/model/describe_index_stats_response.py similarity index 97% rename from pinecone/core/data/client/model/describe_index_stats_response.py rename to pinecone/core/openapi/data/model/describe_index_stats_response.py index 27945d21e..7eb1affcc 100644 --- a/pinecone/core/data/client/model/describe_index_stats_response.py +++ b/pinecone/core/openapi/data/model/describe_index_stats_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.namespace_summary import NamespaceSummary + from pinecone.core.openapi.data.model.namespace_summary import NamespaceSummary globals()["NamespaceSummary"] = NamespaceSummary diff --git a/pinecone/core/data/client/model/fetch_response.py b/pinecone/core/openapi/data/model/fetch_response.py similarity index 97% rename from pinecone/core/data/client/model/fetch_response.py rename to pinecone/core/openapi/data/model/fetch_response.py index 1a3293d47..172deb1c5 100644 --- a/pinecone/core/data/client/model/fetch_response.py +++ b/pinecone/core/openapi/data/model/fetch_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.usage import Usage - from pinecone.core.data.client.model.vector import Vector + from pinecone.core.openapi.data.model.usage import Usage + from pinecone.core.openapi.data.model.vector import Vector globals()["Usage"] = Usage globals()["Vector"] = Vector diff --git a/pinecone/core/data/client/model/list_item.py b/pinecone/core/openapi/data/model/list_item.py similarity index 98% rename from pinecone/core/data/client/model/list_item.py rename to pinecone/core/openapi/data/model/list_item.py index ed3c7049a..66b0b221a 100644 --- a/pinecone/core/data/client/model/list_item.py +++ b/pinecone/core/openapi/data/model/list_item.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class ListItem(ModelNormal): diff --git a/pinecone/core/data/client/model/list_response.py b/pinecone/core/openapi/data/model/list_response.py similarity index 96% rename from pinecone/core/data/client/model/list_response.py rename to pinecone/core/openapi/data/model/list_response.py index 2cf84cda7..8be056e1d 100644 --- a/pinecone/core/data/client/model/list_response.py +++ b/pinecone/core/openapi/data/model/list_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,14 +25,14 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.list_item import ListItem - from pinecone.core.data.client.model.pagination import Pagination - from pinecone.core.data.client.model.usage import Usage + from pinecone.core.openapi.data.model.list_item import ListItem + from pinecone.core.openapi.data.model.pagination import Pagination + from pinecone.core.openapi.data.model.usage import Usage globals()["ListItem"] = ListItem globals()["Pagination"] = Pagination diff --git a/pinecone/core/data/client/model/namespace_summary.py b/pinecone/core/openapi/data/model/namespace_summary.py similarity index 98% rename from pinecone/core/data/client/model/namespace_summary.py rename to pinecone/core/openapi/data/model/namespace_summary.py index d9faed447..5089971af 100644 --- a/pinecone/core/data/client/model/namespace_summary.py +++ b/pinecone/core/openapi/data/model/namespace_summary.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class NamespaceSummary(ModelNormal): diff --git a/pinecone/core/data/client/model/pagination.py b/pinecone/core/openapi/data/model/pagination.py similarity index 98% rename from pinecone/core/data/client/model/pagination.py rename to pinecone/core/openapi/data/model/pagination.py index 485d37aef..4ac4f3c46 100644 --- a/pinecone/core/data/client/model/pagination.py +++ b/pinecone/core/openapi/data/model/pagination.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class Pagination(ModelNormal): diff --git a/pinecone/core/data/client/model/protobuf_any.py b/pinecone/core/openapi/data/model/protobuf_any.py similarity index 98% rename from pinecone/core/data/client/model/protobuf_any.py rename to pinecone/core/openapi/data/model/protobuf_any.py index fad28c252..cf3a97b43 100644 --- a/pinecone/core/data/client/model/protobuf_any.py +++ b/pinecone/core/openapi/data/model/protobuf_any.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class ProtobufAny(ModelNormal): diff --git a/pinecone/core/data/client/model/protobuf_null_value.py b/pinecone/core/openapi/data/model/protobuf_null_value.py similarity index 98% rename from pinecone/core/data/client/model/protobuf_null_value.py rename to pinecone/core/openapi/data/model/protobuf_null_value.py index f7d832578..1d0f06e4a 100644 --- a/pinecone/core/data/client/model/protobuf_null_value.py +++ b/pinecone/core/openapi/data/model/protobuf_null_value.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class ProtobufNullValue(ModelSimple): diff --git a/pinecone/core/data/client/model/query_request.py b/pinecone/core/openapi/data/model/query_request.py similarity index 97% rename from pinecone/core/data/client/model/query_request.py rename to pinecone/core/openapi/data/model/query_request.py index 3989b9acd..71342e332 100644 --- a/pinecone/core/data/client/model/query_request.py +++ b/pinecone/core/openapi/data/model/query_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,13 +25,13 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.query_vector import QueryVector - from pinecone.core.data.client.model.sparse_values import SparseValues + from pinecone.core.openapi.data.model.query_vector import QueryVector + from pinecone.core.openapi.data.model.sparse_values import SparseValues globals()["QueryVector"] = QueryVector globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/data/client/model/query_response.py b/pinecone/core/openapi/data/model/query_response.py similarity index 96% rename from pinecone/core/data/client/model/query_response.py rename to pinecone/core/openapi/data/model/query_response.py index 8b92d93c0..5f211d6dd 100644 --- a/pinecone/core/data/client/model/query_response.py +++ b/pinecone/core/openapi/data/model/query_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,14 +25,14 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.scored_vector import ScoredVector - from pinecone.core.data.client.model.single_query_results import SingleQueryResults - from pinecone.core.data.client.model.usage import Usage + from pinecone.core.openapi.data.model.scored_vector import ScoredVector + from pinecone.core.openapi.data.model.single_query_results import SingleQueryResults + from pinecone.core.openapi.data.model.usage import Usage globals()["ScoredVector"] = ScoredVector globals()["SingleQueryResults"] = SingleQueryResults diff --git a/pinecone/core/data/client/model/query_vector.py b/pinecone/core/openapi/data/model/query_vector.py similarity index 97% rename from pinecone/core/data/client/model/query_vector.py rename to pinecone/core/openapi/data/model/query_vector.py index 3e7b3efbb..42be6a03a 100644 --- a/pinecone/core/data/client/model/query_vector.py +++ b/pinecone/core/openapi/data/model/query_vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.sparse_values import SparseValues + from pinecone.core.openapi.data.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/data/client/model/rpc_status.py b/pinecone/core/openapi/data/model/rpc_status.py similarity index 97% rename from pinecone/core/data/client/model/rpc_status.py rename to pinecone/core/openapi/data/model/rpc_status.py index 2963f0bea..6740060c3 100644 --- a/pinecone/core/data/client/model/rpc_status.py +++ b/pinecone/core/openapi/data/model/rpc_status.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.protobuf_any import ProtobufAny + from pinecone.core.openapi.data.model.protobuf_any import ProtobufAny globals()["ProtobufAny"] = ProtobufAny diff --git a/pinecone/core/data/client/model/scored_vector.py b/pinecone/core/openapi/data/model/scored_vector.py similarity index 97% rename from pinecone/core/data/client/model/scored_vector.py rename to pinecone/core/openapi/data/model/scored_vector.py index 0a92f52e5..c83699bb7 100644 --- a/pinecone/core/data/client/model/scored_vector.py +++ b/pinecone/core/openapi/data/model/scored_vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.sparse_values import SparseValues + from pinecone.core.openapi.data.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/data/client/model/single_query_results.py b/pinecone/core/openapi/data/model/single_query_results.py similarity index 97% rename from pinecone/core/data/client/model/single_query_results.py rename to pinecone/core/openapi/data/model/single_query_results.py index 832a9751e..93147aec6 100644 --- a/pinecone/core/data/client/model/single_query_results.py +++ b/pinecone/core/openapi/data/model/single_query_results.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.scored_vector import ScoredVector + from pinecone.core.openapi.data.model.scored_vector import ScoredVector globals()["ScoredVector"] = ScoredVector diff --git a/pinecone/core/data/client/model/sparse_values.py b/pinecone/core/openapi/data/model/sparse_values.py similarity index 98% rename from pinecone/core/data/client/model/sparse_values.py rename to pinecone/core/openapi/data/model/sparse_values.py index b3b2439b4..7dd915bbb 100644 --- a/pinecone/core/data/client/model/sparse_values.py +++ b/pinecone/core/openapi/data/model/sparse_values.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class SparseValues(ModelNormal): diff --git a/pinecone/core/data/client/model/update_request.py b/pinecone/core/openapi/data/model/update_request.py similarity index 97% rename from pinecone/core/data/client/model/update_request.py rename to pinecone/core/openapi/data/model/update_request.py index 144ccc8c6..2d6bef49a 100644 --- a/pinecone/core/data/client/model/update_request.py +++ b/pinecone/core/openapi/data/model/update_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.sparse_values import SparseValues + from pinecone.core.openapi.data.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/data/client/model/upsert_request.py b/pinecone/core/openapi/data/model/upsert_request.py similarity index 97% rename from pinecone/core/data/client/model/upsert_request.py rename to pinecone/core/openapi/data/model/upsert_request.py index 842009c46..1bce50e3e 100644 --- a/pinecone/core/data/client/model/upsert_request.py +++ b/pinecone/core/openapi/data/model/upsert_request.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.vector import Vector + from pinecone.core.openapi.data.model.vector import Vector globals()["Vector"] = Vector diff --git a/pinecone/core/data/client/model/upsert_response.py b/pinecone/core/openapi/data/model/upsert_response.py similarity index 98% rename from pinecone/core/data/client/model/upsert_response.py rename to pinecone/core/openapi/data/model/upsert_response.py index 2d961e59a..0e0becb3d 100644 --- a/pinecone/core/data/client/model/upsert_response.py +++ b/pinecone/core/openapi/data/model/upsert_response.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class UpsertResponse(ModelNormal): diff --git a/pinecone/core/data/client/model/usage.py b/pinecone/core/openapi/data/model/usage.py similarity index 98% rename from pinecone/core/data/client/model/usage.py rename to pinecone/core/openapi/data/model/usage.py index 26256809f..3125adce0 100644 --- a/pinecone/core/data/client/model/usage.py +++ b/pinecone/core/openapi/data/model/usage.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,8 +25,8 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError class Usage(ModelNormal): diff --git a/pinecone/core/data/client/model/vector.py b/pinecone/core/openapi/data/model/vector.py similarity index 97% rename from pinecone/core/data/client/model/vector.py rename to pinecone/core/openapi/data/model/vector.py index 987ed9f8f..248dc6eb0 100644 --- a/pinecone/core/data/client/model/vector.py +++ b/pinecone/core/openapi/data/model/vector.py @@ -11,7 +11,7 @@ import re # noqa: F401 import sys # noqa: F401 -from pinecone.core.shared.model_utils import ( # noqa: F401 +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 PineconeApiTypeError, ModelComposed, ModelNormal, @@ -25,12 +25,12 @@ none_type, validate_get_composed_info, ) -from pinecone.core.shared.model_utils import OpenApiModel -from pinecone.core.shared.exceptions import PineconeApiAttributeError +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError def lazy_import(): - from pinecone.core.data.client.model.sparse_values import SparseValues + from pinecone.core.openapi.data.model.sparse_values import SparseValues globals()["SparseValues"] = SparseValues diff --git a/pinecone/core/openapi/data/models/__init__.py b/pinecone/core/openapi/data/models/__init__.py new file mode 100644 index 000000000..09a0a48b8 --- /dev/null +++ b/pinecone/core/openapi/data/models/__init__.py @@ -0,0 +1,33 @@ +# 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.data.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from pinecone.core.openapi.data.model.delete_request import DeleteRequest +from pinecone.core.openapi.data.model.describe_index_stats_request import DescribeIndexStatsRequest +from pinecone.core.openapi.data.model.describe_index_stats_response import DescribeIndexStatsResponse +from pinecone.core.openapi.data.model.fetch_response import FetchResponse +from pinecone.core.openapi.data.model.list_item import ListItem +from pinecone.core.openapi.data.model.list_response import ListResponse +from pinecone.core.openapi.data.model.namespace_summary import NamespaceSummary +from pinecone.core.openapi.data.model.pagination import Pagination +from pinecone.core.openapi.data.model.protobuf_any import ProtobufAny +from pinecone.core.openapi.data.model.protobuf_null_value import ProtobufNullValue +from pinecone.core.openapi.data.model.query_request import QueryRequest +from pinecone.core.openapi.data.model.query_response import QueryResponse +from pinecone.core.openapi.data.model.query_vector import QueryVector +from pinecone.core.openapi.data.model.rpc_status import RpcStatus +from pinecone.core.openapi.data.model.scored_vector import ScoredVector +from pinecone.core.openapi.data.model.single_query_results import SingleQueryResults +from pinecone.core.openapi.data.model.sparse_values import SparseValues +from pinecone.core.openapi.data.model.update_request import UpdateRequest +from pinecone.core.openapi.data.model.upsert_request import UpsertRequest +from pinecone.core.openapi.data.model.upsert_response import UpsertResponse +from pinecone.core.openapi.data.model.usage import Usage +from pinecone.core.openapi.data.model.vector import Vector diff --git a/pinecone/core/shared/api_client.py b/pinecone/core/openapi/shared/api_client.py similarity index 99% rename from pinecone/core/shared/api_client.py rename to pinecone/core/openapi/shared/api_client.py index d76e26e74..dda97ec58 100644 --- a/pinecone/core/shared/api_client.py +++ b/pinecone/core/openapi/shared/api_client.py @@ -10,10 +10,10 @@ from urllib3.fields import RequestField -from pinecone.core.shared import rest -from pinecone.core.shared.configuration import Configuration -from pinecone.core.shared.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException -from pinecone.core.shared.model_utils import ( +from pinecone.core.openapi.shared import rest +from pinecone.core.openapi.shared.configuration import Configuration +from pinecone.core.openapi.shared.exceptions import PineconeApiTypeError, PineconeApiValueError, PineconeApiException +from pinecone.core.openapi.shared.model_utils import ( ModelNormal, ModelSimple, ModelComposed, diff --git a/pinecone/core/shared/configuration.py b/pinecone/core/openapi/shared/configuration.py similarity index 99% rename from pinecone/core/shared/configuration.py rename to pinecone/core/openapi/shared/configuration.py index 3653c30b9..96b9a4a3f 100644 --- a/pinecone/core/shared/configuration.py +++ b/pinecone/core/openapi/shared/configuration.py @@ -5,7 +5,7 @@ import urllib3 from http import client as http_client -from pinecone.core.shared.exceptions import PineconeApiValueError +from pinecone.core.openapi.shared.exceptions import PineconeApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { @@ -87,7 +87,7 @@ class Configuration(object): You can programmatically set the cookie: - conf = pinecone.core.control.client.Configuration( + conf = pinecone.core.openapi.control.Configuration( api_key={'cookieAuth': 'abc123'} api_key_prefix={'cookieAuth': 'JSESSIONID'} ) @@ -155,7 +155,7 @@ def __init__( self.logger = {} """Logging Settings """ - self.logger["package_logger"] = logging.getLogger("pinecone.core.control.client") + self.logger["package_logger"] = logging.getLogger("pinecone.core.openapi.control") self.logger["urllib3_logger"] = logging.getLogger("urllib3") self.logger_format = "%(asctime)s %(levelname)s %(message)s" """Log format diff --git a/pinecone/core/shared/exceptions.py b/pinecone/core/openapi/shared/exceptions.py similarity index 100% rename from pinecone/core/shared/exceptions.py rename to pinecone/core/openapi/shared/exceptions.py diff --git a/pinecone/core/shared/model_utils.py b/pinecone/core/openapi/shared/model_utils.py similarity index 99% rename from pinecone/core/shared/model_utils.py rename to pinecone/core/openapi/shared/model_utils.py index baf00e3b4..2e457d245 100644 --- a/pinecone/core/shared/model_utils.py +++ b/pinecone/core/openapi/shared/model_utils.py @@ -6,7 +6,7 @@ import re import tempfile -from pinecone.core.shared.exceptions import ( +from pinecone.core.openapi.shared.exceptions import ( PineconeApiKeyError, PineconeApiAttributeError, PineconeApiTypeError, diff --git a/pinecone/core/shared/rest.py b/pinecone/core/openapi/shared/rest.py similarity index 99% rename from pinecone/core/shared/rest.py rename to pinecone/core/openapi/shared/rest.py index 9e49b4f29..2e7a2dcc0 100644 --- a/pinecone/core/shared/rest.py +++ b/pinecone/core/openapi/shared/rest.py @@ -8,7 +8,7 @@ import urllib3 -from pinecone.core.shared.exceptions import ( +from pinecone.core.openapi.shared.exceptions import ( PineconeApiException, UnauthorizedException, ForbiddenException, diff --git a/pinecone/data/index.py b/pinecone/data/index.py index 8adaed504..eec20da52 100644 --- a/pinecone/data/index.py +++ b/pinecone/data/index.py @@ -4,9 +4,9 @@ from pinecone.config import ConfigBuilder -from pinecone.core.data.client.models import SparseValues -from pinecone.core.data.client import ApiClient -from pinecone.core.data.client.models import ( +from pinecone.core.openapi.data.models import SparseValues +from pinecone.core.openapi.data import ApiClient +from pinecone.core.openapi.data.models import ( FetchResponse, QueryRequest, QueryResponse, @@ -23,7 +23,7 @@ DescribeIndexStatsRequest, ListResponse, ) -from pinecone.core.data.client.api.data_plane_api import DataPlaneApi +from pinecone.core.openapi.data.api.data_plane_api import DataPlaneApi from ..utils import setup_openapi_client from .vector_factory import VectorFactory diff --git a/pinecone/data/sparse_vector_factory.py b/pinecone/data/sparse_vector_factory.py index 5b2379a49..dcc7320e2 100644 --- a/pinecone/data/sparse_vector_factory.py +++ b/pinecone/data/sparse_vector_factory.py @@ -11,7 +11,7 @@ SparseValuesDictionaryExpectedError, ) -from pinecone.core.data.client.models import SparseValues +from pinecone.core.openapi.data.models import SparseValues class SparseValuesFactory: diff --git a/pinecone/data/vector_factory.py b/pinecone/data/vector_factory.py index 1d1fbf468..8734633a2 100644 --- a/pinecone/data/vector_factory.py +++ b/pinecone/data/vector_factory.py @@ -7,7 +7,7 @@ from ..utils.constants import REQUIRED_VECTOR_FIELDS, OPTIONAL_VECTOR_FIELDS from .sparse_vector_factory import SparseValuesFactory -from pinecone.core.data.client.models import Vector, SparseValues +from pinecone.core.openapi.data.models import Vector, SparseValues from .errors import ( VectorDictionaryMissingKeysError, diff --git a/pinecone/exceptions/__init__.py b/pinecone/exceptions/__init__.py index f1e5e55fd..b7148eb04 100644 --- a/pinecone/exceptions/__init__.py +++ b/pinecone/exceptions/__init__.py @@ -1,4 +1,4 @@ -from pinecone.core.shared.exceptions import ( +from pinecone.core.openapi.shared.exceptions import ( PineconeException, PineconeApiAttributeError, PineconeApiTypeError, diff --git a/pinecone/exceptions/exceptions.py b/pinecone/exceptions/exceptions.py index 81bcbd8cf..95de292f9 100644 --- a/pinecone/exceptions/exceptions.py +++ b/pinecone/exceptions/exceptions.py @@ -1,4 +1,4 @@ -from pinecone.core.shared.exceptions import ( +from pinecone.core.openapi.shared.exceptions import ( PineconeException ) diff --git a/pinecone/exceptions/openapi_exceptions.py b/pinecone/exceptions/openapi_exceptions.py new file mode 100644 index 000000000..cd6fa470e --- /dev/null +++ b/pinecone/exceptions/openapi_exceptions.py @@ -0,0 +1,150 @@ +# These exceptions are copied out of the generated openapi client code. +# They have been copied here so that we can have a single source of truth +# for exceptions and avoid having multiple classes with the same name +# as we generate more packages from the openapi specs. + +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): + """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): + """ + 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): + """ + 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): + """ + 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): + 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})\n" "Reason: {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): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(PineconeApiException): + + def __init__(self, status=None, reason=None, http_resp=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/grpc/index_grpc.py b/pinecone/grpc/index_grpc.py index 5bafaee22..e0db9641f 100644 --- a/pinecone/grpc/index_grpc.py +++ b/pinecone/grpc/index_grpc.py @@ -13,7 +13,7 @@ ) from .vector_factory_grpc import VectorFactoryGRPC -from pinecone.core.data.client.models import ( +from pinecone.core.openapi.data.models import ( FetchResponse, QueryResponse, DescribeIndexStatsResponse, diff --git a/pinecone/grpc/utils.py b/pinecone/grpc/utils.py index e3720a365..b0981a3e7 100644 --- a/pinecone/grpc/utils.py +++ b/pinecone/grpc/utils.py @@ -7,7 +7,7 @@ def _generate_request_id() -> str: return str(uuid.uuid4()) -from pinecone.core.data.client.models import ( +from pinecone.core.openapi.data.models import ( Vector as _Vector, Usage, ScoredVector, diff --git a/pinecone/models/collection_list.py b/pinecone/models/collection_list.py index 2d0b9e1b2..9b788ceeb 100644 --- a/pinecone/models/collection_list.py +++ b/pinecone/models/collection_list.py @@ -1,4 +1,4 @@ -from pinecone.core.control.client.models import ( +from pinecone.core.openapi.control.models import ( CollectionList as OpenAPICollectionList, ) diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py index 6fa5aaf51..d9823e219 100644 --- a/pinecone/models/index_list.py +++ b/pinecone/models/index_list.py @@ -1,4 +1,4 @@ -from pinecone.core.control.client.models import IndexList as OpenAPIIndexList +from pinecone.core.openapi.control.models import IndexList as OpenAPIIndexList class IndexList: diff --git a/tests/integration/data/test_openapi_configuration.py b/tests/integration/data/test_openapi_configuration.py index 59e68deb9..c5ca3ca2a 100644 --- a/tests/integration/data/test_openapi_configuration.py +++ b/tests/integration/data/test_openapi_configuration.py @@ -2,7 +2,7 @@ import os from pinecone import Pinecone -from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration +from pinecone.core.openapi.shared.configuration import Configuration as OpenApiConfiguration from urllib3 import make_headers diff --git a/tests/unit/models/test_collection_list.py b/tests/unit/models/test_collection_list.py index 49338fa4f..f62de2487 100644 --- a/tests/unit/models/test_collection_list.py +++ b/tests/unit/models/test_collection_list.py @@ -1,6 +1,6 @@ import pytest from pinecone import CollectionList -from pinecone.core.control.client.models import CollectionList as OpenApiCollectionList, CollectionModel +from pinecone.core.openapi.control.models import CollectionList as OpenApiCollectionList, CollectionModel @pytest.fixture diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py index 57ccabd6c..548c672c8 100644 --- a/tests/unit/models/test_index_list.py +++ b/tests/unit/models/test_index_list.py @@ -1,6 +1,6 @@ import pytest from pinecone import IndexList -from pinecone.core.control.client.models import IndexList as OpenApiIndexList +from pinecone.core.openapi.control.models import IndexList as OpenApiIndexList @pytest.fixture diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 3d03a0c54..c274f90e8 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,7 +1,7 @@ from pinecone import Pinecone from pinecone.exceptions.exceptions import PineconeConfigurationError from pinecone.config import PineconeConfig -from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration +from pinecone.core.openapi.shared.configuration import Configuration as OpenApiConfiguration import pytest import os diff --git a/tests/unit/test_config_builder.py b/tests/unit/test_config_builder.py index 445eea656..0e8399608 100644 --- a/tests/unit/test_config_builder.py +++ b/tests/unit/test_config_builder.py @@ -1,6 +1,6 @@ import pytest -from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration +from pinecone.core.openapi.shared.configuration import Configuration as OpenApiConfiguration from pinecone.config import ConfigBuilder from pinecone import PineconeConfigurationError diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index 12ac400fb..dd869a69c 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -2,9 +2,9 @@ import re from unittest.mock import patch, MagicMock from pinecone import ConfigBuilder, Pinecone, PodSpec, ServerlessSpec -from pinecone.core.control.client.models import IndexList, IndexModel -from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.shared.configuration import Configuration as OpenApiConfiguration +from pinecone.core.openapi.control.models import IndexList, IndexModel +from pinecone.core.openapi.control.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.openapi.shared.configuration import Configuration as OpenApiConfiguration import time diff --git a/tests/unit/utils/test_setup_openapi_client.py b/tests/unit/utils/test_setup_openapi_client.py index b46e3bfe4..e5bafb69b 100644 --- a/tests/unit/utils/test_setup_openapi_client.py +++ b/tests/unit/utils/test_setup_openapi_client.py @@ -1,8 +1,8 @@ import pytest import re from pinecone.config import ConfigBuilder -from pinecone.core.control.client.api.manage_indexes_api import ManageIndexesApi -from pinecone.core.shared.api_client import ApiClient +from pinecone.core.openapi.control.api.manage_indexes_api import ManageIndexesApi +from pinecone.core.openapi.shared.api_client import ApiClient from pinecone.utils.setup_openapi_client import setup_openapi_client, build_plugin_setup_client From 5ab73f99252c070f9609c1d430522d299772079e Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 26 Jun 2024 18:05:16 -0400 Subject: [PATCH 10/13] Fix lint errors --- pinecone/exceptions/__init__.py | 2 +- pinecone/exceptions/exceptions.py | 6 +- pinecone/exceptions/openapi_exceptions.py | 150 ---------------------- tests/unit/test_control.py | 14 +- 4 files changed, 12 insertions(+), 160 deletions(-) delete mode 100644 pinecone/exceptions/openapi_exceptions.py diff --git a/pinecone/exceptions/__init__.py b/pinecone/exceptions/__init__.py index b7148eb04..65e1309d7 100644 --- a/pinecone/exceptions/__init__.py +++ b/pinecone/exceptions/__init__.py @@ -30,4 +30,4 @@ "ForbiddenException", "ServiceException", "ListConversionException", -] \ No newline at end of file +] diff --git a/pinecone/exceptions/exceptions.py b/pinecone/exceptions/exceptions.py index 95de292f9..d7ba3acc6 100644 --- a/pinecone/exceptions/exceptions.py +++ b/pinecone/exceptions/exceptions.py @@ -1,6 +1,5 @@ -from pinecone.core.openapi.shared.exceptions import ( - PineconeException -) +from pinecone.core.openapi.shared.exceptions import PineconeException + class PineconeProtocolError(PineconeException): """Raised when something unexpected happens mid-request/response.""" @@ -13,4 +12,3 @@ class PineconeConfigurationError(PineconeException): class ListConversionException(PineconeException, TypeError): def __init__(self, message): super().__init__(message) - diff --git a/pinecone/exceptions/openapi_exceptions.py b/pinecone/exceptions/openapi_exceptions.py deleted file mode 100644 index cd6fa470e..000000000 --- a/pinecone/exceptions/openapi_exceptions.py +++ /dev/null @@ -1,150 +0,0 @@ -# These exceptions are copied out of the generated openapi client code. -# They have been copied here so that we can have a single source of truth -# for exceptions and avoid having multiple classes with the same name -# as we generate more packages from the openapi specs. - -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): - """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): - """ - 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): - """ - 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): - """ - 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): - 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})\n" "Reason: {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): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(PineconeApiException): - - def __init__(self, status=None, reason=None, http_resp=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/tests/unit/test_control.py b/tests/unit/test_control.py index dd869a69c..a39718fa0 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -118,16 +118,19 @@ def test_create_index_with_timeout( assert p.index_api.describe_index.call_count == expected_describe_index_calls assert time.sleep.call_count == expected_sleep_calls - @pytest.mark.parametrize('index_spec', [ - {"serverless": {"cloud": "aws", "region": "us-west1"}}, - {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1, "replicas": 1, "shards": 1}}, - ]) + @pytest.mark.parametrize( + "index_spec", + [ + {"serverless": {"cloud": "aws", "region": "us-west1"}}, + {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1, "replicas": 1, "shards": 1}}, + ], + ) def test_create_index(self, mocker, index_spec): p = Pinecone(api_key="123-456-789") mock_api = MagicMock() mocker.patch.object(p, "index_api", mock_api) - + p.create_index(name="my-index", dimension=10, spec=index_spec) mock_api.create_index.assert_called_once() @@ -185,6 +188,7 @@ def test_api_key_and_openapi_config(self, mocker): p = Pinecone(api_key="123", openapi_config=OpenApiConfiguration.get_default_copy()) assert p.config.api_key == "123" + class TestIndexConfig: def test_default_pool_threads(self): pc = Pinecone(api_key="123-456-789") From 3712a96a5c4599058ad718acd3908356173c688e Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Thu, 27 Jun 2024 10:31:25 -0400 Subject: [PATCH 11/13] Add build command to Makefile --- Makefile | 21 +++------------------ codegen/build-oas.sh | 10 ++++------ 2 files changed, 7 insertions(+), 24 deletions(-) diff --git a/Makefile b/Makefile index b908e931d..92dcb1d08 100644 --- a/Makefile +++ b/Makefile @@ -24,6 +24,9 @@ test-grpc-unit: make type-check: poetry run mypy pinecone --exclude pinecone/core +make generate-oas: + ./codegen/build-oas.sh "2024-07" + version: poetry version @@ -32,21 +35,3 @@ package: upload: poetry publish --verbose --username ${PYPI_USERNAME} --password ${PYPI_PASSWORD} - -upload-spruce: - # Configure Poetry for publishing to testpypi - poetry config repositories.test-pypi https://test.pypi.org/legacy/ - poetry publish --verbose -r test-pypi --username ${PYPI_USERNAME} --password ${PYPI_PASSWORD} - -license: - # Add license header using https://github.com/google/addlicense. - # If the license header already exists in a file, re-running this command has no effect. - pushd ${mkfile_path}/pinecone && \ - docker run --rm -it -v ${mkfile_path}/pinecone:/src ghcr.io/google/addlicense:latest -f ./license_header.txt *.py */*.py */*/*.py */*/*/*.py */*/*/*/*.py */*/*/*/*/*.py */*/*/*/*/*/*.py; \ - popd - -set-production: - echo "production" > pinecone/__environment__ - -set-development: - echo "" > pinecone/__environment__ diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index d4af30efd..cdf29c1a8 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -2,13 +2,11 @@ set -eux -o pipefail -version='2024-07' +version=$1 # e.g. 2024-07 modules=("control" "data") destination="pinecone/core/openapi" - -rm -rf build -mkdir build +build_dir="build" update_apis_repo() { echo "Updating apis repo" @@ -59,14 +57,14 @@ generate_client() { # Cleanup previous build files echo "Cleaning up previous build files" - rm -rf build + rm -rf "${build_dir}" # Generate client module docker run --rm -v $(pwd):/workspace openapitools/openapi-generator-cli:v5.2.0 generate \ --input-spec "/workspace/$oas_file" \ --generator-name python \ --config "/workspace/$openapi_generator_config" \ - --output /workspace/build \ + --output "/workspace/${build_dir}" \ --template-dir "/workspace/$template_dir" # Copy the generated module to the correct location From 7f3805ac0bb6b67c4330869ebf2ae8d5db1b6ba2 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Thu, 27 Jun 2024 13:45:47 -0400 Subject: [PATCH 12/13] Add more tests for passing index spec as dict --- pinecone/control/pinecone.py | 16 +++++++++++++++- tests/unit/test_control.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 4d75f5b9d..426687095 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -324,7 +324,21 @@ def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: if "serverless" in spec: index_spec = IndexSpec(serverless=ServerlessSpecModel(**spec["serverless"])) elif "pod" in spec: - index_spec = IndexSpec(pod=PodSpecModel(**spec["pod"])) + 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): diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index a39718fa0..ec8100459 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -122,10 +122,34 @@ def test_create_index_with_timeout( "index_spec", [ {"serverless": {"cloud": "aws", "region": "us-west1"}}, - {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1, "replicas": 1, "shards": 1}}, + {"serverless": {"cloud": "aws", "region": "us-west1", "uknown_key": "value"}}, + {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1"}}, + {"pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "unknown_key": "value"}}, + { + "pod": { + "environment": "us-west1-gcp", + "pod_type": "p1.x1", + "pods": 2, + "replicas": 1, + "shards": 1, + "metadata_config": {"indexed": ["foo"]}, + "source_collection": "bar", + } + }, + { + "pod": { + "environment": "us-west1-gcp", + "pod_type": "p1.x1", + "pods": None, + "replicas": None, + "shards": None, + "metadata_config": None, + "source_collection": None, + } + }, ], ) - def test_create_index(self, mocker, index_spec): + def test_create_index_with_spec_dictionary(self, mocker, index_spec): p = Pinecone(api_key="123-456-789") mock_api = MagicMock() From 5a72002f83c318a27662c638841e9ec868932844 Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Wed, 3 Jul 2024 17:47:08 -0400 Subject: [PATCH 13/13] Automatically pull updates to template repo as well --- codegen/apis | 2 +- codegen/build-oas.sh | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/codegen/apis b/codegen/apis index 04a751307..fbd9d8d48 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit 04a7513074c893ee005004598cfbbbbad4f07138 +Subproject commit fbd9d8d48c95b12c6b28aea4e496b6f28666d2d1 diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index cdf29c1a8..08074538a 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -17,6 +17,14 @@ update_apis_repo() { popd } +update_templates_repo() { + echo "Updating templates repo" + pushd codegen/python-oas-templates + git fetch + git pull + popd +} + verify_spec_version() { local version=$1 echo "Verifying spec version $version exists in apis repo" @@ -121,6 +129,7 @@ extract_shared_classes() { } update_apis_repo +update_templates_repo verify_spec_version $version rm -rf "${destination}"