### Complete Pinecone Quickstart Example Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/getting-started/quickstart.md A comprehensive example demonstrating the full workflow: client initialization, index creation, vector upsertion, querying, and index deletion. ```python from pinecone import Pinecone, ServerlessSpec pc = Pinecone() # reads PINECONE_API_KEY pc.indexes.create( name="quickstart", dimension=3, metric="cosine", spec=ServerlessSpec(cloud="aws", region="us-east-1"), ) index = pc.index("quickstart") index.upsert(vectors=[ ("id1", [0.1, 0.2, 0.3]), ("id2", [0.4, 0.5, 0.6]), ("id3", [0.7, 0.8, 0.9]), ]) results = index.query(vector=[0.1, 0.2, 0.3], top_k=3) for match in results.matches: print(match.id, match.score) pc.indexes.delete("quickstart") ``` -------------------------------- ### Install Development Dependencies with uv Source: https://github.com/pinecone-io/python-sdk/blob/main/README.md Install development dependencies for the Pinecone Python SDK using uv sync. ```bash uv sync ``` -------------------------------- ### Start and Monitor Bulk Import Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-index.md Starts a bulk import from cloud storage and polls for its completion status. Use this for large datasets that need to be imported asynchronously. ```python import asyncio # Start an import and poll until complete response = await idx.start_import(uri="s3://my-bucket/vectors/") import_id = response.id import_op = await idx.describe_import(import_id) while import_op.status not in ("Completed", "Failed", "Cancelled"): await asyncio.sleep(10) import_op = await idx.describe_import(import_id) print(f"Status: {import_op.status}, records imported: {import_op.records_imported}") ``` -------------------------------- ### Install Pinecone Python SDK Source: https://github.com/pinecone-io/python-sdk/blob/main/README.md Install the Pinecone Python SDK using pip. For development dependencies, use the 'dev' extra. ```bash pip install pinecone ``` ```bash pip install pinecone[dev] ``` -------------------------------- ### Install python-dotenv Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/getting-started/authentication.md Install the python-dotenv package to load environment variables from a local .env file. ```bash pip install python-dotenv ``` -------------------------------- ### Install Pinecone with uv Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/getting-started/installation.md Use uv, a fast Python package installer, to add the Pinecone Python client library to your project. ```bash uv add pinecone ``` -------------------------------- ### Create a Preview Index Asynchronously Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/preview.md This example shows how to create a new preview index using the `AsyncPreviewIndexes` namespace. It requires a schema definition and an index name. ```python pc = AsyncPinecone(api_key="...") index = await pc.preview.indexes.create( schema={"fields": {"embedding": {"type": "dense_vector", "dimension": 1536}}}, name="my-preview-index", ) ``` -------------------------------- ### Pinecone SDK Initialization and Upsert/Search Example Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/models.md Demonstrates initializing the Pinecone client, upserting records, and performing a search operation. It also shows how to access committed LSN for reconciliation. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") index = pc.index(host="product-search.svc.pinecone.io") upsert_resp = index.upsert_records( namespace="electronics", records=[{"id": "prod-42", "_text": "wireless headphones"}], ) committed_lsn = upsert_resp.response_info.lsn_committed query_resp = index.search( namespace="electronics", inputs={"text": "headphones"}, ) query_resp.result.response_info.is_reconciled(committed_lsn) ``` -------------------------------- ### List All Backups Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Initializes the Pinecone client and retrieves a list of all backups in the project. Use this to get an overview of all available backups. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") ids = [b.backup_id for b in pc.backups.list()] ``` -------------------------------- ### Initialize Pinecone Index Client Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/vectors/upsert-and-query.md First, initialize the Pinecone client and get an index client. Replace 'your-api-key' with your actual API key and 'movie-recommendations' with your index name. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") index = pc.index("movie-recommendations") ``` -------------------------------- ### Start a Bulk Import Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/vectors/bulk-import.md Initiates a server-side bulk import from a specified URI in cloud storage. Returns an operation ID immediately. ```APIDOC ## Start an import `start_import()` initiates the operation and returns immediately with an operation ID: ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") index = pc.index("product-search") response = index.start_import(uri="s3://my-bucket/embeddings/") import_id = response.id print(import_id) # e.g. "1" ``` `uri` points to a directory prefix, not an individual file. ``` -------------------------------- ### start_import Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/sync-index.md Starts a bulk import operation from an external data source into a Pinecone index. The import runs server-side and can be monitored using `describe_import()`. ```APIDOC ## start_import(uri, error_mode=None, integration_id=None) ### Description Start a bulk import operation from an external data source. Initiates an asynchronous bulk import of vectors from cloud storage into the index. The import runs server-side; use [`describe_import()`](#pinecone.index.Index.describe_import) to poll for progress and completion. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method POST (implied) ### Endpoint /indexes/{index_name}/import ### Parameters * **uri** (*str*) – Source URI for the import data (e.g. `"s3://my-bucket/vectors/"` or `"gs://my-bucket/vectors/"`). * **error_mode** (*str* *|* *None*) – How to handle errors during import. Must be `"continue"` or `"abort"` when supplied. Case-insensitive. Optional; when omitted the backend default (`"continue"`) applies. * **integration_id** (*str* *|* *None*) – Optional integration ID for the import. ### Returns `StartImportResponse` with the ID of the created import operation. ### Raises * [**PineconeValueError**](exceptions.md#pinecone.errors.exceptions.PineconeValueError) – If `error_mode` is supplied but not `"continue"` or `"abort"`. * [**ApiError**](exceptions.md#pinecone.errors.exceptions.ApiError) – If the API returns an error response. * [**PineconeConnectionError**](exceptions.md#pinecone.errors.exceptions.PineconeConnectionError) – If a network-level connection fails (DNS, refused, transport error). * [**PineconeTimeoutError**](exceptions.md#pinecone.errors.exceptions.PineconeTimeoutError) – If the request exceeds the configured timeout. ### Return type [*StartImportResponse*](models.md#pinecone.models.imports.model.StartImportResponse) ### Examples ```python # Start an import and poll until complete response = idx.start_import(uri="s3://my-bucket/vectors/") import_id = response.id # Poll until the import finishes import_op = idx.describe_import(import_id) while import_op.status not in ("Completed", "Failed", "Cancelled"): time.sleep(10) import_op = idx.describe_import(import_id) print(f"Status: {import_op.status}, records imported: {import_op.records_imported}") # Abort on first error instead of continuing response = idx.start_import( uri="s3://my-bucket/vectors/", error_mode="abort", ) ``` ``` -------------------------------- ### Query an Index Asynchronously Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client, get an index, and perform an asynchronous query. The client and index are managed using async context managers. ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.index(name="my-index") async with index: results = await index.query( vector=[0.012, -0.087, 0.153, ...], # 1536-dim embedding top_k=10, ) ``` -------------------------------- ### Create Serverless Pinecone Index Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Example of creating a serverless Pinecone index with a specified name, dimension, and serverless configuration. ```python >>> from pinecone import Pinecone, ServerlessSpec >>> pc = Pinecone(api_key="your-api-key") >>> index = pc.indexes.create( ... name="movie-recommendations", ... dimension=1536, ... spec=ServerlessSpec(cloud="aws", region="us-east-1"), ... ) ``` -------------------------------- ### Describe Preview Index Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/preview.md Use this to get information about a preview index, such as its host URL. Requires an initialized Pinecone client. ```python >>> from pinecone import Pinecone >>> pc = Pinecone(api_key="your-api-key") >>> info = pc.preview.indexes.describe("articles-en-preview") >>> print(info.host) ``` -------------------------------- ### Start a Bulk Import Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/vectors/bulk-import.md Initiates a server-side bulk import operation from a specified cloud storage URI. Returns an operation ID immediately. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") index = pc.index("product-search") response = index.start_import(uri="s3://my-bucket/embeddings/") import_id = response.id print(import_id) # e.g. "1" ``` -------------------------------- ### Configure Pinecone Index Settings Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Examples of configuring existing Pinecone indexes with different parameters such as replicas, tags, and serverless read capacity. ```python >>> pc.indexes.configure("my-index", replicas=4) >>> pc.indexes.configure("my-index", tags={"env": "prod"}) >>> pc.indexes.configure("my-index", serverless_read_capacity={"mode": "OnDemand"}) ``` -------------------------------- ### Get Index Host for Data Plane Client Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Shows how to obtain the host for an index to create a data plane client. This is necessary because AsyncPinecone.index() cannot auto-resolve the host by name. ```default desc = await pc.indexes.describe("my-index") idx = pc.index("my-index") # uses cached host # — or — idx = pc.index(host=desc.host) # explicit host ``` -------------------------------- ### Initialize AsyncPinecone and List Collections Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client using an API key and then list all available collections. ```python async with AsyncPinecone(api_key="your-api-key") as pc: for col in await pc.collections.list(): print(col.name) ``` -------------------------------- ### Verify Pinecone Installation Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/getting-started/installation.md Confirm the Pinecone Python client library is installed correctly by checking its version. This command imports the library and prints the installed version number. ```python python -c "import pinecone; print(pinecone.__version__)" ``` -------------------------------- ### Initialize and Use AsyncPinecone Client Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client within an async context manager and perform basic operations like describing an index and querying data. ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: desc = await pc.indexes.describe("my-index") index = pc.index(host=desc.host) async with index: results = await index.query( vector=[0.012, -0.087, 0.153], top_k=10, ) ``` -------------------------------- ### AsyncPinecone Initialization and Usage Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client and use it to describe an index and perform a query. ```APIDOC ## AsyncPinecone Initialization and Usage ### Description This example shows the basic usage pattern for the `AsyncPinecone` client. It initializes the client within an `async with` statement, accesses the `indexes` sub-client to describe an index, and then uses the data-plane client to perform a vector query. ### Method Asynchronous context manager (`async with`) ### Endpoint N/A (SDK client initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: desc = await pc.indexes.describe("my-index") index = pc.index(host=desc.host) async with index: results = await index.query( vector=[0.012, -0.087, 0.153], top_k=10, ) ``` ### Response #### Success Response (200) - `desc`: An object containing index description details, including its host. - `results`: The results of the vector query. #### Response Example ```json { "desc": { "host": "your-index-host.pinecone.io" }, "results": { "matches": [ { "id": "example-id", "score": 0.9, "values": [], "metadata": {} } ], "namespace": "" } } ``` ### Class: AsyncPinecone #### Description Asynchronous Pinecone client for control-plane operations. This client manages indexes, collections, backups, and related resources asynchronously. #### Parameters * **api_key** (*str* | *None*): Pinecone API key. Falls back to `PINECONE_API_KEY` env var. * **host** (*str* | *None*): Control-plane API host. Falls back to `PINECONE_CONTROLLER_HOST` env var, then defaults to `https://api.pinecone.io`. * **additional_headers** (*Mapping*[*str*, *str*] | *None*): Extra headers included in every request. * **source_tag** (*str* | *None*): Tag appended to the User-Agent string for request attribution. * **proxy_url** (*str* | *None*): HTTP proxy URL for outgoing requests. * **proxy_headers** (*Mapping*[*str*, *str*] | *None*): Not yet supported. Raises `NotImplementedError` if provided. * **ssl_ca_certs** (*str* | *None*): Path to a CA certificate bundle for SSL verification. * **ssl_verify** (*bool*): Whether to verify SSL certificates. Defaults to `True`. * **timeout** (*float*): Request timeout in seconds. Defaults to `30.0`. * **connection_pool_maxsize** (*int*): Maximum number of connections to keep in the pool. `0` (default) uses httpx defaults. * **retry_config** (*RetryConfig* | *None*): Custom retry configuration. When `None` (default), uses built-in defaults (5 attempts, exponential backoff, retries on 500/502/503/504 for GET/HEAD). #### Raises * **PineconeValueError**: If no API key can be resolved from arguments or environment variables. ``` -------------------------------- ### Install Pinecone with pip Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/getting-started/installation.md Use pip to install the Pinecone Python client library. Ensure you have Python 3.10 or higher. ```bash pip install pinecone ``` -------------------------------- ### Create a pod-based index with multiple replicas and pods Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/indexes/pod.md Example of creating a pod-based index with multiple replicas for availability and query throughput, and multiple pods for total storage capacity. ```APIDOC ## Multiple replicas and pods Replicas increase availability and query throughput. Pods control total storage capacity: ```python from pinecone import Pinecone, PodSpec pc = Pinecone(api_key="your-api-key") pc.indexes.create( name="product-search-ha", dimension=1536, metric="cosine", spec=PodSpec( environment="us-east1-gcp", pod_type="p1.x1", pods=2, replicas=2, ), ) ``` ``` -------------------------------- ### AsyncPinecone Initialization and Index Query Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client using an API key and perform a query on an index within an asynchronous context manager. ```APIDOC ## AsyncPinecone Initialization and Index Query ### Description Initializes the `AsyncPinecone` client with an API key and demonstrates how to access an index and perform a query. This example utilizes the asynchronous context manager for proper resource management. ### Method `AsyncPinecone` constructor and `index().query()` ### Endpoint N/A (SDK method) ### Parameters #### AsyncPinecone Constructor Parameters - **api_key** (str | None) - Your Pinecone API key. - **host** (str | None) - Optional host override. - **additional_headers** (Mapping[str, str] | None) - Additional headers to send with requests. - **source_tag** (str | None) - Tag for the source of the request. - **proxy_url** (str | None) - URL for a proxy server. - **proxy_headers** (Mapping[str, str] | None) - Headers for the proxy server. - **ssl_ca_certs** (str | None) - Path to SSL CA certificates. - **ssl_verify** (bool) - Whether to verify SSL certificates. Defaults to True. - **timeout** (float) - Request timeout in seconds. Defaults to 30.0. - **connection_pool_maxsize** (int) - Maximum size of the connection pool. Defaults to 0. - **retry_config** (RetryConfig | None) - Configuration for retries. #### index() Parameters - **name** (str) - The name of the index to connect to. #### query() Parameters - **vector** (list[float]) - The embedding vector to query with. - **top_k** (int) - The number of nearest neighbors to return. ### Request Example ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.index(name="my-index") async with index: results = await index.query( vector=[0.012, -0.087, 0.153, ...], # 1536-dim embedding top_k=10, ) ``` ### Response #### Success Response (query) - **results** (dict) - The query results, typically containing `matches`. ``` -------------------------------- ### Create a Preview Index Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/preview.md Use this to create a new preview index with a specified schema and optional configurations like name, deployment, and read capacity. The index may not be immediately ready after creation; poll its status using `describe()`. ```python index = await pc.preview.indexes.create( schema={"fields": {"embedding": {"type": "dense_vector", "dimension": 1536}}}, name="my-preview-index", ) ``` -------------------------------- ### Access Model Resource for Listing and Getting Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Use the lazily-initialized model resource to list all models or get information for a specific model. Requires an initialized AsyncPinecone client. ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: models = await pc.inference.model.list() info = await pc.inference.model.get("multilingual-e5-large") ``` -------------------------------- ### Initialize Admin Client and Create Project Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/admin.md Demonstrates initializing the Admin client with OAuth2 credentials and creating a new project. This is part of a common workflow to set up projects and API keys before using the Pinecone client for data operations. ```default from pinecone import Admin, Pinecone, ServerlessSpec admin = Admin(client_id="...", client_secret="...") project = admin.projects.create(name="my-project") key = admin.api_keys.create(project_id=project.id, name="my-key") pc = Pinecone(api_key=key.value) pc.indexes.create(name="my-index", dimension=1536, metric="cosine", spec=ServerlessSpec(cloud="aws", region="us-east-1")) ``` -------------------------------- ### List Backups Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/models.md Lists available backups for a specified index. The returned object has a `names()` method to get a list of backup names and a `to_dict()` method to get a dictionary representation. ```APIDOC ## list_backups ### Description Lists available backups for a specified index. ### Method GET ### Endpoint /databases/{database}/indexes/{index_name}/backups ### Parameters #### Path Parameters - **database** (string) - Required - The name of the database. - **index_name** (string) - Required - The name of the index to list backups for. ### Request Example ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") backups = pc.list_backups(index_name="movie-recommendations") ``` ### Response #### Success Response (200) - **names** (list[str]) - A list of backup names. - **to_dict()** (dict) - A dictionary representation of the backups, potentially including pagination info. #### Response Example ```python # Example of backups.names() ['daily-2025-01-01', 'weekly-2024-12-29'] # Example of backups.to_dict() {'data': [{'backup_id': 'bkp-abc123', ...}, {'backup_id': 'bkp-def456', ...}]} ``` ``` -------------------------------- ### Initialize AsyncIndex and Describe Stats Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-index.md Demonstrates how to initialize an AsyncIndex either by resolving the host automatically using the index name or by directly providing the host URL. It then shows how to retrieve index statistics using describe_index_stats(). ```python from pinecone import AsyncPinecone pc = AsyncPinecone(api_key="your-api-key") # Resolve host automatically by index name async with await pc.index("my-index") as idx: stats = await idx.describe_index_stats() # — or — connect directly with a host URL async with AsyncIndex(host="my-index-abc123.svc.pinecone.io", api_key="...") as idx: stats = await idx.describe_index_stats() ``` -------------------------------- ### AsyncIndex Initialization Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-index.md Demonstrates how to initialize an AsyncIndex object with host and API key. ```APIDOC ## AsyncIndex ### Description Initializes an asynchronous index client for interacting with a Pinecone index. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **host** (str) - The data plane host URL for the Pinecone index. * **api_key** (str | None) - Your Pinecone API key. * **additional_headers** (Mapping[str, str] | None) - Additional headers to send with requests. * **timeout** (float) - Request timeout in seconds. Defaults to 30.0. * **proxy_url** (str | None) - URL for a proxy server. * **proxy_headers** (Mapping[str, str] | None) - Headers for the proxy server. * **ssl_ca_certs** (str | None) - Path to SSL CA certificates. * **ssl_verify** (bool) - Whether to verify SSL certificates. Defaults to True. * **source_tag** (str | None) - Tag for the source of the request. * **connection_pool_maxsize** (int) - Maximum size of the connection pool. * **_limiter_registry** (_AdaptiveLimiterRegistry | None) - Internal limiter registry. ### Return type: None ``` -------------------------------- ### Get Data-Plane Index: v8 vs v9 Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/migration/v9-migration.md Shows the change in how to get a data-plane index object from v8 to v9. Note the case change and deprecation of `pc.Index()` in v9. ```python pc.Index("name") ``` ```python pc.index("name") ``` -------------------------------- ### Start Import with Abort on Error Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/grpc.md Starts a bulk import from S3, configured to abort immediately if any errors occur during the process. Use this when data integrity is critical and partial imports are unacceptable. ```python response = idx.start_import( uri="s3://my-bucket/vectors/", error_mode="abort", ) ``` -------------------------------- ### AsyncPinecone Client Initialization and Index Listing Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the asynchronous Pinecone client and list available indexes. ```APIDOC ## AsyncPinecone Client Initialization and Index Listing ### Description Initializes the asynchronous Pinecone client using an API key and lists all available indexes. ### Method `AsyncPinecone` constructor and `indexes.list()` method. ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python async with AsyncPinecone(api_key="your-api-key") as pc: for idx in await pc.indexes.list(): print(idx.name) ``` ### Response #### Success Response An iterable of index objects, each containing index details. #### Response Example (Output depends on existing indexes, e.g., printing index names) ``` -------------------------------- ### describe Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Get detailed information about a named collection. ```APIDOC ## describe ### Description Get detailed information about a named collection. ### Method GET ### Endpoint /collections/{name} ### Parameters #### Path Parameters - **name** (str) - Required - The name of the collection to describe. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **CollectionModel** - With name, status, size, dimension, vector_count, and environment. #### Response Example ```json { "name": "my-collection", "status": "Ready", "size": 1024, "dimension": 1536, "vector_count": 1000, "environment": "gcp-starter" } ``` ### Errors - **ValidationError**: If *name* is empty. - **NotFoundError**: If the collection does not exist. - **ApiError**: If the API returns another error response. ``` -------------------------------- ### Quick Start: Pinecone Python SDK Usage Source: https://github.com/pinecone-io/python-sdk/blob/main/README.md Initialize the Pinecone client, create a serverless index, upsert vectors, and query for similar vectors. Ensure your API key is set. ```python from pinecone import Pinecone, ServerlessSpec # Initialize the client pc = Pinecone(api_key="your-api-key") # Create a serverless index pc.indexes.create( name="movie-recommendations", dimension=1536, metric="cosine", spec=ServerlessSpec(cloud="aws", region="us-east-1"), ) # Connect to the index index = pc.index("movie-recommendations") # Upsert vectors index.upsert( vectors=[ ("movie-42", [0.012, -0.087, 0.153]), # 1536-dim embedding ("movie-87", [0.045, 0.021, -0.064]), # 1536-dim embedding ], namespace="movies-en", batch_size=100, # split larger inputs into parallel batches automatically ) # Query for similar vectors results = index.query( vector=[0.012, -0.087, 0.153], # 1536-dim embedding top_k=10, namespace="movies-en", ) for match in results.matches: print(f"{match.id}: {match.score:.4f}") ``` -------------------------------- ### Get Backup Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Retrieves details for a specific backup using its ID. ```APIDOC ## Get Backup ### Description Retrieves details for a specific backup using its ID. ### Method GET ### Endpoint /v1/backups/{backup_id} ### Parameters #### Path Parameters - **backup_id** (string) - Required - The ID of the backup to retrieve. ### Response #### Success Response (200) - **status** (string) - The status of the backup. ### Response Example ```json { "status": "succeeded" } ``` ``` -------------------------------- ### Create Indexes with AsyncPinecone Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates creating two types of indexes: a standard serverless index and an integrated index with embedding configuration. Ensure you have an API key and specify the cloud and region. ```python async with AsyncPinecone(api_key="your-api-key") as pc: await pc.indexes.create( name="my-index", dimension=1536, spec=ServerlessSpec(cloud="aws", region="us-east-1"), ) await pc.indexes.create( name="my-integrated-index", spec=IntegratedSpec( cloud="aws", region="us-east-1", embed=EmbedConfig( model="multilingual-e5-large", field_map={"text": "my_text_field"}, ), ), ) ``` -------------------------------- ### Pinecone Client Initialization and Usage Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Demonstrates how to initialize the Pinecone client using an API key and use it as a context manager for automatic resource cleanup. It also shows how to list indexes. ```APIDOC ## Pinecone Client Initialization and Usage ### Description Initializes the Pinecone client and demonstrates its usage within a context manager, ensuring resources are properly closed after use. It also shows how to list available indexes. ### Method `Pinecone(api_key: str, ...)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pinecone import Pinecone with Pinecone(api_key="your-api-key") as pinecone_client: _ = pinecone_client.indexes.list() ``` ### Response #### Success Response N/A (SDK method) #### Response Example N/A ``` -------------------------------- ### Describe Restore Job Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Gets detailed information about a specific restore job. ```APIDOC ## Describe Restore Job ### Description Gets detailed information about a specific restore job. ### Method GET ### Endpoint /v1/restore-jobs/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The identifier of the restore job to describe. ### Response #### Success Response (200) - **restore_job_id** (string) - The ID of the restore job. - **status** (string) - The status of the restore job. ### Response Example ```json { "restore_job_id": "rj-restore-20240115", "status": "succeeded" } ``` ``` -------------------------------- ### Get Model Information Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Retrieves detailed information about a specific inference model. ```APIDOC ## get_model(, model=None, **kwargs) Get detailed information about a specific model. * **Parameters:** * **model** (*str*) – The model identifier to look up. * **kwargs** (*str*) * **Returns:** A `ModelInfo` with full model details. * **Raises:** * [**PineconeValueError**](exceptions.md#pinecone.errors.exceptions.PineconeValueError) – If *model* is empty. * [**NotFoundError**](exceptions.md#pinecone.errors.exceptions.NotFoundError) – If the model does not exist. * [**ApiError**](exceptions.md#pinecone.errors.exceptions.ApiError) – If the API returns another error response. * [**PineconeConnectionError**](exceptions.md#pinecone.errors.exceptions.PineconeConnectionError) – If a network-level connection fails (DNS, refused, transport error). * [**PineconeTimeoutError**](exceptions.md#pinecone.errors.exceptions.PineconeTimeoutError) – If the request exceeds the configured timeout. * **Return type:** [ModelInfo](models.md#pinecone.models.inference.models.ModelInfo) ``` -------------------------------- ### Create and Inspect BackupModel Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/models.md Demonstrates how to instantiate a BackupModel with essential details and convert it to a dictionary. Use this to represent a single index backup. ```python from pinecone.models.backups.model import BackupModel backup = BackupModel( backup_id="bkp-1", source_index_name="my-index", source_index_id="idx-abc", status="Ready", cloud="aws", region="us-east-1", name="weekly-backup", ) d = backup.to_dict() d["backup_id"] 'bkp-1' d["name"] 'weekly-backup' d["description"] is None True ``` -------------------------------- ### Run Full Smoke Suite with All Opt-in Paths Source: https://github.com/pinecone-io/python-sdk/blob/main/tests/smoke/README.md Execute all smoke tests, including every opt-in path. Set environment variables for specific opt-in features like pod shims, backups, and imports. ```bash # Full + every opt-in path SMOKE_RUN_POD_SHIMS=1 SMOKE_RUN_BACKUPS=1 \ PINECONE_IMPORT_S3_URI=s3://my-bucket/data.parquet \ PINECONE_IMPORT_INTEGRATION_ID=int-abc123 \ uv run --with python-dotenv --with pytest-asyncio pytest tests/smoke/ -v -s ``` -------------------------------- ### describe Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Get detailed information about a specific restore job using its unique identifier. ```APIDOC ## describe ### Description Get detailed information about a restore job. ### Method Not specified (SDK method) ### Parameters #### Path Parameters * **job_id** (str) - Required - The identifier of the restore job to describe. ### Response #### Success Response Returns a `RestoreJobModel` with full restore job details. ### Raises * **ValidationError** – If *job_id* is empty. * **NotFoundError** – If the restore job does not exist. * **ApiError** – If the API returns another error response. ``` -------------------------------- ### Create Index with Async Preview Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Illustrates creating an index using the asynchronous preview namespace. Note that preview features may change and are not covered by SemVer. ```python async with AsyncPinecone(api_key="your-api-key") as pc: await pc.preview.indexes.create(...) # when a preview area exists ``` -------------------------------- ### Get an Index Handle Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/integrated-records.md Obtain a handle to an existing Pinecone index for subsequent operations. ```python index = pc.index("articles") ``` -------------------------------- ### StartImportResponse Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/models.md Response model for starting a bulk import operation, containing the unique identifier for the created import. ```APIDOC ## Class: StartImportResponse ### Description Response model for starting a bulk import operation. ### Variables * **id** (*str*) – Unique identifier for the created import operation. ### Parameters * **id** (*str*) - Required ### Attributes * **id** : str ``` -------------------------------- ### Chat Completions (Streaming) Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Example of how to perform a streaming chat completion using the asynchronous Pinecone client. ```APIDOC ## Streaming chat completion ### Description Performs a streaming chat completion, receiving chunks of the response as they are generated. ### Method `await pc.assistants.chat_completions(...)` ### Parameters * **assistant_name** (str) - Required - Name of the assistant to interact with. * **messages** (list[dict]) - Required - A list of message objects, where each message has a 'content' field. * **stream** (bool) - Required - Set to `True` to enable streaming. ### Request Example ```python async def stream_main() -> None: stream = await pc.assistants.chat_completions( assistant_name="research-assistant", messages=[{"content": "Explain quantum entanglement briefly."}] stream=True ) async for chunk in stream: print(chunk) asyncio.run(stream_main()) ``` ### Response #### Success Response Yields chunks of the chat completion response as they become available. ``` -------------------------------- ### Index Client Initialization Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/sync-index.md Demonstrates how to initialize a synchronous Index client instance. You can either resolve the host automatically by providing the index name or connect directly using a host URL. ```APIDOC ## Index Client Initialization Obtain an `Index` instance via [`pinecone.Pinecone.index()`](pinecone.md#pinecone.Pinecone.index). ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") # Resolve host automatically by index name idx = pc.index("my-index") # — or — connect directly with a host URL idx = pc.index(host="my-index-abc123.svc.pinecone.io") ``` ### Class: pinecone.index.Index Synchronous data plane client targeting a specific Pinecone index. Can be constructed directly with a host URL, or via the `Pinecone.index()` factory method. #### Parameters: * **host** (*str*) – The index-specific data plane host URL. * **api_key** (*str* | *None*) – Pinecone API key. Falls back to `PINECONE_API_KEY` env var. * **additional_headers** (*Mapping*[*str*, *str*] | *None*) – Extra headers included in every request. * **timeout** (*float*) – Request timeout in seconds. Defaults to `30.0`. * **proxy_url** (*str* | *None*) – HTTP proxy URL for outgoing requests. * **ssl_ca_certs** (*str* | *None*) – Path to a CA certificate bundle for SSL verification. * **ssl_verify** (*bool*) – Whether to verify SSL certificates. Defaults to `True`. * **source_tag** (*str* | *None*) – Tag appended to the User-Agent string for request attribution. * **connection_pool_maxsize** (*int*) – Maximum number of connections to keep in the pool. `0` (default) uses httpx defaults. * **pool_threads** (*int* | *None*) – Tune the thread pool used by the legacy `async_req=True` execution model on `upsert`, `query`, `describe_index_stats`, and `list_paginated`. Defaults to `10`. The pool is lazy-constructed on first `async_req=True` call and shut down by [`close()`](#pinecone.index.Index.close); `multiprocessing.pool` is not imported until then. **For new code, prefer** [`AsyncIndex`](async-index.md#pinecone.async_client.async_index.AsyncIndex) **or** `concurrent.futures.ThreadPoolExecutor`. This kwarg exists for backcompat with pre-rewrite callers. * **proxy_headers** (*Mapping*[*str*, *str*] | *None*) * **kwargs** (*Any*) #### Raises: [**PineconeValueError**](exceptions.md#pinecone.errors.exceptions.PineconeValueError) – If no API key can be resolved or the host is invalid. ``` -------------------------------- ### Initialize AsyncPinecone Client Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client using an API key within an asynchronous context manager. This is the entry point for using asynchronous Pinecone operations. ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: assistants = pc.assistants ``` -------------------------------- ### Chat Completions (Non-streaming) Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Example of how to perform a non-streaming chat completion using the asynchronous Pinecone client. ```APIDOC ## Non-streaming chat completion ### Description Performs a non-streaming chat completion by sending messages to a specified assistant. ### Method `await pc.assistants.chat_completions(...)` ### Parameters * **assistant_name** (str) - Required - Name of the assistant to interact with. * **messages** (list[dict]) - Required - A list of message objects, where each message has a 'content' field. * **stream** (bool) - Optional - Set to `False` for non-streaming responses. ### Request Example ```python import asyncio from pinecone import AsyncPinecone pc = AsyncPinecone(api_key="your-api-key") async def main() -> None: response = await pc.assistants.chat_completions( assistant_name="research-assistant", messages=[{"content": "Explain quantum entanglement briefly."}] ) print(response.choices[0].message.content) asyncio.run(main()) ``` ### Response #### Success Response Returns a chat completion response object containing the assistant's reply. ``` -------------------------------- ### Upsert Embeddings into an Index Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/inference/embeddings.md Example of extracting raw embedding values and upserting them into a standard Pinecone index. ```python index = pc.index("product-search") vectors = [ (f"doc-{i}", emb.values) for i, emb in enumerate(result.data) ] index.upsert(vectors=vectors) ``` -------------------------------- ### Create a new project Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/admin.md Use this to create a new project. Ensure you have the necessary client credentials. The project name must be unique. ```python from pinecone import Admin admin = Admin(client_id="your-client-id", client_secret="your-client-secret") project = admin.projects.create(name="my-project") project.name ``` -------------------------------- ### Quick Start: Create, Upsert, and Query Index Source: https://github.com/pinecone-io/python-sdk/blob/main/AGENTS.md This snippet demonstrates the basic workflow of creating a serverless index, upserting vectors, and querying for similar vectors using the Pinecone Python SDK. Ensure the PINECONE_API_KEY environment variable is set. ```python import os from pinecone import Pinecone, ServerlessSpec pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"]) # Create a serverless index pc.indexes.create( name="movie-recommendations", dimension=1536, metric="cosine", spec=ServerlessSpec(cloud="aws", region="us-east-1"), ) # Get a handle to the index (data-plane operations) index = pc.index("movie-recommendations") # Upsert vectors index.upsert(vectors=[ ("movie-42", [0.012, -0.087, 0.153]), # 1536-dim vector ("movie-43", [0.045, 0.021, -0.064]), # 1536-dim vector ]) # Query by vector similarity results = index.query(vector=[0.012, -0.087, 0.153], top_k=5) # 1536-dim vector for match in results.matches: print(match.id, match.score) ``` -------------------------------- ### Access Sparse Embeddings Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/inference/embeddings.md Example for models that return sparse embeddings, showing how to access `sparse_indices` and `sparse_values`. ```python result = pc.inference.embed( model="pinecone-sparse-english-v0", inputs=["machine learning frameworks"], ) sparse = result.data[0] print(sparse.sparse_indices) print(sparse.sparse_values) ``` -------------------------------- ### Get Inference Model Information Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Initialize the Pinecone client and retrieve information about a specific inference model. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") model_info = pc.inference.get_model(model="multilingual-e5-large") print(model_info.type) ``` -------------------------------- ### Initialize AsyncPinecone Client and Generate Embeddings Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/async-pinecone.md Demonstrates how to initialize the AsyncPinecone client and generate embeddings for a given text input using a specified model. Ensure you have your API key configured. ```python from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: embeddings = await pc.inference.embed( model="multilingual-e5-large", inputs=["Hello, world!"] ) ``` -------------------------------- ### get Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md Retrieves detailed information about a specific backup using its backup ID. This is an alias for the `describe` method. ```APIDOC ## get Get detailed information about a backup (alias for `describe`). ### Parameters * **backup_id** (*str*) – The identifier of the backup. ### Returns A `BackupModel` with full backup details. ### Raises * **ValidationError** – If *backup_id* is empty. * **NotFoundError** – If the backup does not exist. * **ApiError** – If the API returns another error response. ### Return type BackupModel ``` -------------------------------- ### List Projects Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/admin.md Instantiate the Admin client and iterate through accessible projects. ```python >>> from pinecone import Admin >>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret") >>> for project in admin.projects.list(): ... print(project.name) ``` -------------------------------- ### Describe a Specific Assistant Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/assistant.md Get detailed information about a single assistant by its name. This includes its status and instructions. ```python asst = pc.assistants.describe(name="my-assistant") print(asst.name) # "my-assistant" print(asst.status) # "Ready" print(asst.instructions) # the instruction string ``` -------------------------------- ### Paginate through backups Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/indexes/backups-and-restore.md Demonstrates how to paginate through backup lists using `limit` and `pagination_token` for efficient retrieval of large backup sets. ```python page = pc.backups.list(limit=5) if page.pagination and page.pagination.next: next_page = pc.backups.list(limit=5, pagination_token=page.pagination.next) ``` -------------------------------- ### Delete a Pinecone Assistant Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md This example shows how to delete a Pinecone assistant by its name. The SDK polls to confirm deletion. ```python >>> assistant = pc.assistants.delete(name="my-assistant") ``` -------------------------------- ### Retrieve Model Information Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/pinecone.md This example shows how to fetch detailed information about a specific inference model using its identifier. ```python pc.inference.get_model(model="multilingual-e5-large") ``` -------------------------------- ### Create a basic backup Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/how-to/indexes/backups-and-restore.md Initiates a backup of a specified index. The backup ID and initial status are returned. ```python from pinecone import Pinecone pc = Pinecone(api_key="your-api-key") backup = pc.backups.create(index_name="product-search") print(backup.backup_id) # e.g. "bk-abc123" print(backup.status) # e.g. "Initializing" ``` -------------------------------- ### Run Fast Subset of Smoke Tests Source: https://github.com/pinecone-io/python-sdk/blob/main/tests/smoke/README.md Execute a prioritized subset of smoke tests. Ensure pytest and pytest-asyncio are installed. ```bash cd sdks/python-sdk2 # Fast subset (priorities 1+2) uv run --with python-dotenv --with pytest-asyncio pytest \ tests/smoke/test_inference_sync.py \ tests/smoke/test_inference_async.py \ tests/smoke/test_deprecated_shims_sync.py \ tests/smoke/test_deprecated_shims_async.py -v -s ``` -------------------------------- ### Initialize and Close Preview Index Source: https://github.com/pinecone-io/python-sdk/blob/main/docs/reference/preview.md Demonstrates how to initialize a preview index using a host URL and subsequently close it. ```APIDOC ## Initialize and Close Preview Index ### Description Initializes a preview index using a provided host URL and demonstrates how to close the index connection. ### Method `pc.preview.index(host: str)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python >>> import asyncio >>> from pinecone import Pinecone >>> pc = Pinecone(api_key="your-api-key") >>> async def main() -> None: ... index = pc.preview.index(host="https://my-index.svc.pinecone.io") ... await index.close() >>> asyncio.run(main()) ``` ### Response #### Success Response (200) None #### Response Example None ```