Models

All public model types returned by SDK methods. Every model is an immutable msgspec.Struct subclass — fields are accessed as plain attributes (e.g. idx.name).

Index Models

class pinecone.models.indexes.index.IndexModel(*, name, status, schema, deployment, deletion_protection, host=None, read_capacity=None, tags=None, private_host=None, source_collection=None, source_backup_id=None, cmek_id=None)[source]

Bases: Struct

Everything the control plane knows about one index.

What describe, create and configure return, and what iterating list yields. Two fields carry most of the traffic: status.ready is what you poll to know the index can serve requests, and host is what you hand to Pinecone.index() to get a data-plane client. Everything about the index’s shape — dimension, metric, which fields are searchable — is in schema.

Variables:
Parameters:

Examples

>>> idx = pc.indexes.describe("my-index")
>>> idx.status.ready, idx.deployment.cloud, idx.deployment.region
(True, 'aws', 'us-east-1')
>>> index = pc.index(host=idx.host)

IndexModel also reads like a mapping: index["host"] and "host" in index work for every attribute above, and to_dict() returns the same key set.

Changed in version 10.0: dimension, metric, vector_type, spec, embed and created_at are no longer plain attributes.

The first five survive as deprecated properties computed from the fields above: dimension, metric and vector_type resolve when the schema has exactly one vector field, spec rebuilds the 9.x IndexSpec from deployment, read_capacity and schema, and embed rebuilds the 9.x ModelIndexEmbed from the schema’s semantic text field. Every spelling agrees: index.metric, index["metric"], "metric" in index and the "metric" key of to_dict() all answer from the same lookup. Where an accessor is ambiguous — two dense fields, say — the attribute raises AttributeError, the item access raises KeyError carrying that same explanation, in is False, and to_dict() omits the key.

created_at is genuinely gone, because the 2026-07 API does not return a creation timestamp. Reading it raises AttributeError, and index["created_at"] a KeyError, saying so.

name: str
status: IndexStatus
schema: IndexSchema
deployment: ManagedDeployment | PodDeployment | ByocDeployment
deletion_protection: str
host: str | None
read_capacity: ReadCapacityOnDemandResponse | ReadCapacityDedicatedResponse | None
tags: dict[str, str] | None
private_host: str | None
source_collection: str | None
source_backup_id: str | None
cmek_id: str | None
property dimension: int | None

Width of the schema’s sole dense vector field.

None for a sparse-only schema, since sparse vectors have no fixed dimension. Raises AttributeError when the schema has more than one dense field, or no vector field at all: there is no single field to resolve to, and the message says which fields it found.

Also readable as index["dimension"], testable with "dimension" in index, and present in to_dict() — all three resolve exactly when this property does.

Deprecated since version 10.0: Read index.schema.fields["<field-name>"].dimension instead.

property metric: str

Metric of the schema’s sole dense vector field.

Resolves to "dotproduct" for a schema whose only vector field is sparse, since sparse scoring is always dot product. Raises AttributeError when more than one field could answer.

Also readable as index["metric"], testable with "metric" in index, and present in to_dict() — all three resolve exactly when this property does.

Deprecated since version 10.0: Read index.schema.fields["<field-name>"].metric instead.

property vector_type: str

"dense" or "sparse", for a schema with one vector field.

Raises AttributeError when the schema has several fields of one kind — a hybrid schema has no single vector type to report.

Also readable as index["vector_type"], testable with "vector_type" in index, and present in to_dict() — all three resolve exactly when this property does.

Deprecated since version 10.0: Inspect the field types in index.schema.fields instead.

property spec: IndexSpec

The index’s placement, in the 9.x spec shape.

An IndexSpec with exactly one of serverless, pod and byoc set, chosen by deployment.deployment_type, so 9.x reads like index.spec.serverless.region and index.spec.pod.pod_type keep working. Every value is copied out of deployment, read_capacity, schema and source_collection — nothing here is fetched, and the object is rebuilt on each access rather than cached.

pod.metadata_config is always None: metadata is indexed automatically at upsert, so 2026-07 has no such configuration to report. pod.pods is computed as replicas * shards, the same identity the create path enforces when translating a 9.x pods=.

Examples

>>> idx = pc.indexes.describe("my-index")
>>> idx.spec.serverless.cloud, idx.spec.serverless.region
('aws', 'us-east-1')

Deprecated since version 10.0: Branch on deployment with isinstance() instead — ManagedDeployment, PodDeployment and ByocDeployment carry the same values with one less level of nesting, and read capacity is top-level at read_capacity.

property embed: ModelIndexEmbed | None

Integrated-embedding configuration, in the 9.x embed shape.

A ModelIndexEmbed built from the schema’s sole SemanticTextField, so 9.x reads like index.embed.model and index.embed.field_map keep working. None for an index with no semantic text field, which is what 9.x reported for a non-integrated index.

dimension and vector_type are always None: a 2026-07 semantic_text field reports neither, and inventing them would mean guessing. Raises AttributeError when the schema has more than one semantic text field, naming them — as with metric, there is no single field to resolve to.

Examples

>>> idx = pc.indexes.describe("my-integrated-index")
>>> idx.embed.model, idx.embed.field_map
('multilingual-e5-large', {'text': 'chunk_text'})

Deprecated since version 10.0: Read the SemanticTextField out of index.schema.fields instead.

to_dict()[source]

Return the whole model as nested plain dicts, for logging or JSON.

status, schema, deployment and read_capacity become dicts too, each keeping the key that identifies which variant it is (deployment_type, mode, type). A LegacyMetadataField is emitted without a type, matching the wire format. Optional fields that are None are present with a None value rather than omitted, so the key set is the same for every index.

The deprecated dimension, metric, vector_type, spec and embed keys are included whenever the like-named property resolves, which is the key set 9.x emitted. spec and embed are nested dicts, so d["spec"]["serverless"]["region"] reads as it did in 9.x. An index whose schema makes a key ambiguous omits it rather than guessing, and created_at is never emitted.

The result is still accepted by msgspec.convert(d, IndexModel), which ignores the derived keys. It is not constructor input: IndexModel(**d) rejects them, and never built a usable model anyway, since the nested values are dicts rather than the structs the fields are typed as.

Return type:

dict[str, Any]

class pinecone.models.indexes.list.IndexList(indexes)[source]

Bases: object

The indexes that the legacy pc.list_indexes() hands back.

A thin sequence of IndexModel: iterate it, subscript it, take its len(), or call names(). Not constructed directly.

New code should call pc.indexes.list(), which returns a Paginator instead — the same iteration, without materialising every index up front.

Examples

>>> for idx in pc.list_indexes():
...     print(idx.name, idx.status.ready)
Parameters:

indexes (list[IndexModel])

__init__(indexes)[source]
Parameters:

indexes (list[IndexModel])

Return type:

None

property indexes: list[IndexModel]

The underlying list, when you need a real list to hold on to.

to_dict()[source]

Return the listing as nested plain dicts, for logging or JSON.

Returns:

A dict with a single "data" key holding one entry per index, each the output of IndexModel.to_dict.

Return type:

dict[str, Any]

Examples

>>> list(pc.list_indexes().to_dict())
['data']
names()[source]

Just the index names, in the order the server returned them.

Return type:

list[str]

class pinecone.models.indexes.index.IndexStatus(*, ready, state)[source]

Bases: StructDictMixin, Struct

Whether an index can serve requests yet, and what it is busy doing.

Branch on ready; read state when you want to say why an index is not ready, or to distinguish a scaling operation from a failed initialization.

Variables:
  • ready (bool) – Whether the index accepts requests. This is the field to poll, and the one create waits on for you unless you passed timeout=-1.

  • state (str) – What the index is doing, as a readable label — "Initializing", "InitializationFailed", "ScalingUp", "ScalingDown", "ScalingUpPodSize", "ScalingDownPodSize", "Terminating", "Ready", or "Disabled". An index can report ready while a scaling state is in progress, so the two answer different questions.

Parameters:
ready: bool
state: str
class pinecone.models.indexes.index.IndexTags[source]

Bases: dict

An index’s tags: an ordinary dict, plus to_dict() for symmetry.

IndexModel wraps whatever tags come back in this so that every nested model on the response answers to_dict().

to_dict()[source]
Return type:

dict[str, str]

class pinecone.models.indexes.specs.ServerlessSpec(*, cloud, region, read_capacity=None, schema=None)[source]

Bases: StructDictMixin, Struct

A serverless index, described the 9.x way.

Deprecated sugar for create()’s spec=: the SDK turns it into a managed deployment=, lifting any read_capacity out to the top level as it goes. spec= and deployment= are mutually exclusive.

Variables:
  • cloud (str) – Public cloud to run in, e.g. "aws".

  • region (str) – Region within that cloud, e.g. "us-east-1".

  • read_capacity (dict[str, Any] | None) – Read capacity configuration, or None for the default.

  • schema (dict[str, Any] | None) – Not translated. A schema set here does not reach the create request, and a create() call that relied on it fails with PineconeValueError saying schema is required — which reads as though you passed none. Pass schema= to create() directly.

Parameters:

Deprecated since version 10.0: Pass deployment={"deployment_type": "managed", "cloud": ..., "region": ...} instead.

cloud: str
region: str
read_capacity: dict[str, Any] | None
schema: dict[str, Any] | None
asdict()[source]

Return the 9.x request shape, {"serverless": {...}}.

Return type:

dict[str, Any]

class pinecone.models.indexes.specs.PodSpec(*, environment, pod_type='p1.x1', replicas=1, shards=1, pods=1, metadata_config=None, source_collection=None)[source]

Bases: StructDictMixin, Struct

A pod-based index, described the 9.x way.

Deprecated sugar for create()’s spec=, translated into a pod deployment=. spec= and deployment= are mutually exclusive. The struct still carries every 9.x field so an old spec object survives a round trip, but two of them have nowhere to go in a create request and are rejected rather than dropped.

Variables:
  • environment (str) – The environment hosting the index, e.g. "us-east-1-aws".

  • pod_type (str) – Hardware family and size. Defaults to "p1.x1".

  • replicas (int) – How many copies of the index to run. Defaults to 1.

  • shards (int) – How many pods to split the data across. Defaults to 1.

  • pods (int) – Total pod count, kept only for 9.x compatibility. Leave it at its default of 1 or set it to exactly replicas * shards; anything else raises PineconeValueError, because there is no independent pod count to translate it into.

  • metadata_config (dict[str, Any] | None) – Rejected with PineconeTypeError when set — metadata fields are indexed automatically at upsert, so there is nothing to declare at create time.

  • source_collection (str | None) – Rejected with PineconeTypeError when set. Use Pinecone.create_index_from_backup to restore a backup instead.

Parameters:
  • environment (str)

  • pod_type (str)

  • replicas (int)

  • shards (int)

  • pods (int)

  • metadata_config (dict[str, Any] | None)

  • source_collection (str | None)

Deprecated since version 10.0: Pass deployment={"deployment_type": "pod", "environment": ..., "pod_type": ..., "replicas": ..., "shards": ...} instead.

environment: str
pod_type: str
replicas: int
shards: int
pods: int
metadata_config: dict[str, Any] | None
source_collection: str | None
asdict()[source]

Return the 9.x request shape, {"pod": {...}}.

Return type:

dict[str, Any]

class pinecone.models.indexes.specs.ByocSpec(*, environment, read_capacity=None, schema=None)[source]

Bases: StructDictMixin, Struct

A BYOC index, described the 9.x way.

Deprecated sugar for create()’s spec=, translated into a BYOC deployment= with any read_capacity lifted to the top level. spec= and deployment= are mutually exclusive.

Variables:
  • environment (str) – The BYOC environment to run in, e.g. "aws-us-east-1-b921".

  • read_capacity (dict[str, Any] | None) – Read capacity configuration, or None for the default.

  • schema (dict[str, Any] | None) – Not translated, exactly as on ServerlessSpec. Pass schema= to create() directly.

Parameters:

Deprecated since version 10.0: Pass deployment={"deployment_type": "byoc", "environment": ...} instead.

environment: str
read_capacity: dict[str, Any] | None
schema: dict[str, Any] | None
asdict()[source]

Return the 9.x request shape, {"byoc": {...}}.

Return type:

dict[str, Any]

class pinecone.models.indexes.specs.IntegratedSpec(*, cloud, region, embed)[source]

Bases: StructDictMixin, Struct

Cloud, region and embedding config bundled into one 9.x-style spec.

Unlike its sibling specs this one has no deployment= translation, so passing it as spec= to create() raises PineconeTypeError rather than being rewritten. Call create_for_model() with cloud, region and embed instead — the same three values, as arguments.

Variables:
Parameters:

Deprecated since version 10.0: Pass cloud=, region= and embed= to create_for_model().

cloud: str
region: str
embed: EmbedConfig
class pinecone.models.indexes.specs.EmbedConfig(*, model, field_map, dimension=None, metric=None, read_parameters=None, write_parameters=None)[source]

Bases: Struct

Which model embeds your text, and which field it reads.

One of the shapes create_for_model() accepts for embed= — a plain dict with the same keys works too. The field it names comes back on the created index as a SemanticTextField, and the model cannot be changed afterwards.

Variables:
  • model (str) – Embedding model to use, e.g. "multilingual-e5-large". See EmbedModel.

  • field_map (dict[str, str]) – Which document field holds the text to embed, as {"text": "<your field name>"} — e.g. {"text": "chunk_text"}.

  • dimension (int | None) – Output width to ask the model for, when it supports more than one. None takes the model’s own dimension. Note that to_dict() omits this field; create_for_model reads the attribute directly, so the create path is unaffected, but a dict you build with to_dict() loses it.

  • metric (str | None) – How similarity is scored, or None for the model default.

  • read_parameters (dict[str, Any] | None) – Extra arguments passed to the model when embedding a query, e.g. {"input_type": "query"}.

  • write_parameters (dict[str, Any] | None) – Extra arguments passed to the model when embedding an upsert, e.g. {"input_type": "passage"}.

Parameters:
model: str
field_map: dict[str, str]
dimension: int | None
metric: str | None
read_parameters: dict[str, Any] | None
write_parameters: dict[str, Any] | None
to_dict()[source]

Serialize to a plain dict of model, field_map and metric.

read_parameters and write_parameters come out as empty dicts rather than being omitted when they were never set, and dimension is left out entirely — pass the EmbedConfig itself to create_for_model, which reads the attribute, rather than the output of this method.

Return type:

dict[str, Any]

Deprecated 9.x Spec Views

What the deprecated spec and embed properties return. Nothing decodes into these classes — each is a view over deployment, read_capacity and schema, kept so 9.x reads like index.spec.serverless.region keep working.

class pinecone.models.indexes.index.IndexSpec(*, serverless=None, pod=None, byoc=None)[source]

Bases: StructDictMixin, Struct

A 9.x-shaped view of where an index runs.

What IndexModel.spec returns. Exactly one of serverless, pod and byoc is set, chosen by the deployment_type of the index’s deployment.

Variables:
Parameters:

Deprecated since version 10.0: Branch on index.deployment with isinstance() instead. The deployment classes carry the same values without a level of nesting, and only they are what the API actually returns.

serverless: ServerlessSpecInfo | None
pod: PodSpecInfo | None
byoc: ByocSpecInfo | None
class pinecone.models.indexes.index.ServerlessSpecInfo(*, cloud, region, read_capacity=None, source_collection=None, schema=None)[source]

Bases: StructDictMixin, Struct

The serverless half of a 9.x index.spec.

Built on demand by IndexModel.spec from a ManagedDeployment plus the index’s top-level read_capacity and schema. Nothing decodes into this class — it is a view over fields that now live elsewhere.

Variables:
  • cloud (str) – Cloud provider, from deployment.cloud.

  • region (str) – Cloud region, from deployment.region.

  • read_capacity (dict[str, Any] | None) – The index’s read_capacity as a plain dict with its "mode" key, or None when the response omits it. 2026-07 carries this at the top level; read IndexModel.read_capacity for the typed object.

  • source_collection (str | None) – The index’s top-level source_collection.

  • schema (dict[str, Any] | None) – The index’s typed schema as a plain dict. Note the shift: in 9.x this key held the metadata-indexing schema and was None by default, whereas the 2026-07 schema declares every field including the vector ones.

Parameters:

Deprecated since version 10.0: Read index.deployment, index.read_capacity and index.schema directly.

cloud: str
region: str
read_capacity: dict[str, Any] | None
source_collection: str | None
schema: dict[str, Any] | None
class pinecone.models.indexes.index.PodSpecInfo(*, environment, pod_type, replicas=None, shards=None, pods=None, metadata_config=None, source_collection=None)[source]

Bases: StructDictMixin, Struct

The pod half of a 9.x index.spec.

Built on demand by IndexModel.spec from a PodDeployment.

Variables:
  • environment (str) – Deployment environment, from deployment.environment.

  • pod_type (str) – Pod type, from deployment.pod_type.

  • replicas (int | None) – Replica count, from deployment.replicas.

  • shards (int | None) – Shard count, from deployment.shards.

  • pods (int | None) – Total pod count, computed as replicas * shards. 2026-07 has no independent pods field; that product is the same identity the create path enforces when translating a 9.x pods=.

  • metadata_config (dict[str, list[str]] | None) – Always None. Metadata fields are indexed automatically at upsert, so 2026-07 neither accepts nor returns a metadata-indexing configuration.

  • source_collection (str | None) – The index’s top-level source_collection.

Parameters:
  • environment (str)

  • pod_type (str)

  • replicas (int | None)

  • shards (int | None)

  • pods (int | None)

  • metadata_config (dict[str, list[str]] | None)

  • source_collection (str | None)

Deprecated since version 10.0: Read index.deployment directly.

environment: str
pod_type: str
replicas: int | None
shards: int | None
pods: int | None
metadata_config: dict[str, list[str]] | None
source_collection: str | None
class pinecone.models.indexes.index.ByocSpecInfo(*, environment, read_capacity=None, schema=None)[source]

Bases: StructDictMixin, Struct

The BYOC half of a 9.x index.spec.

Built on demand by IndexModel.spec from a ByocDeployment plus the index’s top-level read_capacity and schema.

Variables:
  • environment (str) – BYOC environment, from deployment.environment.

  • read_capacity (dict[str, Any] | None) – The index’s read_capacity as a plain dict, or None when the response omits it.

  • schema (dict[str, Any] | None) – The index’s typed schema as a plain dict, with the same semantic shift noted on ServerlessSpecInfo.

Parameters:

Deprecated since version 10.0: Read index.deployment, index.read_capacity and index.schema directly.

environment: str
read_capacity: dict[str, Any] | None
schema: dict[str, Any] | None
class pinecone.models.indexes.index.ModelIndexEmbed(*, model, metric=None, dimension=None, vector_type=None, field_map=None, read_parameters=None, write_parameters=None)[source]

Bases: StructDictMixin, Struct

A 9.x-shaped view of an index’s integrated-embedding configuration.

What IndexModel.embed returns, built from the single SemanticTextField in the index’s schema.

Variables:
  • model (str) – Embedding model, from the semantic field’s model.

  • metric (str | None) – Distance metric, from the semantic field’s metric, or None when the field uses the model’s own default.

  • dimension (int | None) – Always None. A 2026-07 semantic_text field does not report the width of the vectors it produces.

  • vector_type (str | None) – Always None. The field does not say whether its model is dense or sparse, and guessing "dense" would be wrong for a sparse embedding model.

  • field_map (dict[str, str] | None) – {"text": "<field name>"}, rebuilt from the name of the semantic field. create_for_model names the field after the field_map text entry, so this recovers what was passed.

  • read_parameters (dict[str, Any] | None) – From the semantic field’s read_parameters.

  • write_parameters (dict[str, Any] | None) – From the semantic field’s write_parameters.

Parameters:

Deprecated since version 10.0: Read the SemanticTextField out of index.schema.fields instead.

model: str
metric: str | None
dimension: int | None
vector_type: str | None
field_map: dict[str, str] | None
read_parameters: dict[str, Any] | None
write_parameters: dict[str, Any] | None

Index Request Models

class pinecone.models.indexes.requests.CreateIndexRequest(*, schema, name=None, deployment=None, read_capacity=None, deletion_protection=None, tags=None, source_collection=None, source_backup_id=None, cmek_id=None)[source]

Bases: Struct

The body create() sends.

Assembled from that method’s keyword arguments; the field descriptions there are the ones to read. schema is the only required member.

Variables:
Raises:

PineconeValueError – If deployment names a deployment_type outside the three above. The comparison is case-sensitive, so "MANAGED" is rejected as well as a genuine typo.

Parameters:
schema: dict[str, Any] | IndexSchema
name: str | None
deployment: dict[str, Any] | ManagedDeployment | PodDeployment | ByocDeployment | None
read_capacity: dict[str, Any] | None
deletion_protection: str | None
tags: dict[str, str] | None
source_collection: str | None
source_backup_id: str | None
cmek_id: str | None
class pinecone.models.indexes.requests.ConfigureIndexRequest(*, schema=None, deployment=None, read_capacity=None, deletion_protection=None, tags=None)[source]

Bases: Struct

The body configure() sends.

Assembled from that method’s keyword arguments; the field descriptions there are the ones to read. Every member is optional and anything left unset stays out of the request, so a configure changes only what you named.

Variables:
  • schema (dict[str, Any] | pinecone.models.indexes.schema.IndexSchema | None) – Schema changes. Only a semantic_text field’s parameters can be changed; fields cannot be added or removed.

  • deployment (dict[str, Any] | None) – Deployment changes, for pod-based indexes only — replicas and pod_type, with no deployment_type key.

  • read_capacity (dict[str, Any] | None) – Replacement read capacity configuration.

  • deletion_protection (str | None) – "enabled" or "disabled".

  • tags (dict[str, str] | None) – Tags to merge into the existing ones. Setting a key to "" deletes it.

Parameters:
schema: dict[str, Any] | IndexSchema | None
deployment: dict[str, Any] | None
read_capacity: dict[str, Any] | None
deletion_protection: str | None
tags: dict[str, str] | None

Index Schema Models

IndexModel.schema describes every field in the index. These types replace the IndexModel.dimension, .metric, .vector_type and .embed attributes, which survive only as deprecated computed properties.

class pinecone.models.indexes.schema.IndexSchema(*, fields)[source]

Bases: Struct

Every field an index has, and what each one can do.

The schema is where an index’s shape is declared. You pass it as schema= when creating an index and read it back from IndexModel.schema afterwards. Dimension, metric and vector type live inside a field declaration rather than on the index, which is what lets one index carry a dense field, a sparse field and searchable text at the same time.

Each entry in fields names a field type through its type key, and that type is what decides how the field can be searched. A ``schema=`` you pass to :meth:`create <pinecone.client.indexes.Indexes.create>` declares searchable fields, and only those — exactly the three types below. Metadata you merely want to filter on stays out of it: put it in the documents you upsert and it is indexed for filtering automatically. Pass a filter-only field anyway and the client rejects the call with PineconeValueError, saying the schema “looks like a 9.x metadata schema” because none of its fields carry a type.

The remaining types are things you read back, never things you ask for. Declaring one is rejected, and because one bad field fails the whole schema, a single response-only field turns the entire create call into an error rather than being ignored — which is what makes a describe-then-create round-trip fail.

Declarable when you create an index:

dense_vector

A fixed-width vector of floats, scored by a similarity metric. Carries dimension and metric — see DenseVectorField.

sparse_vector

Variable-length index/value pairs for keyword-style scoring, with no dimension and no choice of metric — see SparseVectorField.

string

Text made full-text searchable by a full_text_search config — see StringField.

Read back but not declarable — sending one on create is rejected:

semantic_text

Text Pinecone embeds for you on write and on read. create_for_model() is the only way to get one — see SemanticTextField.

float, boolean, string_list

Numeric, boolean and tag-style metadata, indexed for filtering automatically at upsert time — see FloatField, BooleanField, StringListField.

integer

Numeric metadata on indexes predating the normalisation of numbers to float — see IntegerField.

A field from an index older than typed schemas arrives with no type at all and becomes a LegacyMetadataField.

Note

create_for_model() also takes a schema=, but it is a different, older-shaped parameter: that one does take filter-only metadata fields such as {"fields": {"genre": {"filterable": True}}}, and sends them as given. Everything above describes create()’s schema=.

Variables:

fields (dict[str, pinecone.models.indexes.schema.DenseVectorField | pinecone.models.indexes.schema.SparseVectorField | pinecone.models.indexes.schema.SemanticTextField | pinecone.models.indexes.schema.StringField | pinecone.models.indexes.schema.StringListField | pinecone.models.indexes.schema.BooleanField | pinecone.models.indexes.schema.IntegerField | pinecone.models.indexes.schema.FloatField | pinecone.models.indexes.schema.LegacyMetadataField]) – Field name to its typed definition, one of the types above.

Parameters:

fields (dict[str, DenseVectorField | SparseVectorField | SemanticTextField | StringField | StringListField | BooleanField | IntegerField | FloatField | LegacyMetadataField])

Examples

>>> idx = pc.indexes.describe("semantic-search")
>>> {name: type(f).__name__ for name, f in idx.schema.fields.items()}
{'chunk_text': 'SemanticTextField'}

See also

SchemaBuilder — assembles the schema= dict with one validated method per declarable field type, and refuses the response-only ones before you spend a round trip.

fields: dict[str, DenseVectorField | SparseVectorField | SemanticTextField | StringField | StringListField | BooleanField | IntegerField | FloatField | LegacyMetadataField]
to_dict()[source]

Return the schema as the plain dict the API exchanges.

Typed fields keep their type key; a LegacyMetadataField is emitted without one, matching what the wire format actually looks like. Note that the result still needs its response-only fields removed before it can be passed back to create.

Return type:

dict[str, Any]

pinecone.models.indexes.schema.IndexSchemaField = pinecone.models.indexes.schema.DenseVectorField | pinecone.models.indexes.schema.SparseVectorField | pinecone.models.indexes.schema.SemanticTextField | pinecone.models.indexes.schema.StringField | pinecone.models.indexes.schema.StringListField | pinecone.models.indexes.schema.BooleanField | pinecone.models.indexes.schema.IntegerField | pinecone.models.indexes.schema.FloatField | pinecone.models.indexes.schema.LegacyMetadataField

Union of all schema field types appearing in index responses. Use this as the decode target when parsing a single field from JSON.

class pinecone.models.indexes.schema.DenseVectorField(*, dimension, metric, description=None)[source]

Bases: Struct

A fixed-width vector of floats, scored by similarity.

The workhorse field type, and what a semantic search index is built on. Declare one per embedding model you intend to search with. Its type in a schema= dict is "dense_vector"; constructing this class instead sets that for you.

Variables:
  • dimension (int) – Width of the vector, matching the embedding model that produces it, e.g. 1536. Must be between 1 and 20000 — SchemaBuilder rejects anything outside that range before the request leaves the client.

  • metric (str) – How similarity is scored — "cosine", "dotproduct", or "euclidean". Fixed for the life of the field; see Metric for how to choose.

  • description (str | None) – Free-text note about the field, or None when none was given. Always present in responses.

Parameters:
  • dimension (int)

  • metric (str)

  • description (str | None)

Examples

The schema= entry that declares one:

{"embedding": {"type": "dense_vector", "dimension": 1536,
               "metric": "cosine"}}
dimension: int
metric: str
description: str | None
class pinecone.models.indexes.schema.SparseVectorField(*, description=None)[source]

Bases: Struct

Variable-length index/value pairs, for keyword-style scoring.

Where a dense field compares meaning, a sparse field compares terms, so an index that needs both declares both. There is nothing to configure: a sparse field has no dimension because it is variable-length, and no metric because sparse scoring is not adjustable. Its type in a schema= dict is "sparse_vector".

A hybrid index has to declare its sparse field up front. The field cannot be added later by configure, so an index created without one has to be recreated.

Variables:

description (str | None) – Free-text note about the field, or None.

Parameters:

description (str | None)

Examples

The schema= entry that declares one:

{"keywords": {"type": "sparse_vector"}}
description: str | None
class pinecone.models.indexes.schema.SemanticTextField(*, model, metric=None, description=None, read_parameters=None, write_parameters=None)[source]

Bases: Struct

Text that Pinecone embeds for you, on write and on read.

With a semantic text field you upsert and query plain text and never handle a vector yourself — the difference from DenseVectorField, where producing the embedding is your job.

Response-only, and there is exactly one way to get one: create_for_model(), which names the field after the field_map text entry. Writing "type": "semantic_text" into a schema= you pass to create is not the other way — the client sends it and the server rejects it, and because one bad field fails the whole schema the index is not created at all. The 9.x spec=IntegratedSpec(...) route is gone too; it raises PineconeTypeError naming create_for_model as the replacement. The model cannot be changed once the index exists.

Variables:
  • model (str) – Embedding model doing the work, e.g. "multilingual-e5-large".

  • metric (str | None) – How similarity is scored, or None when the field uses the model’s own default.

  • description (str | None) – Free-text note about the field, or None.

  • read_parameters (dict[str, Any] | None) – Extra arguments passed to the model when embedding a query, e.g. {"input_type": "query"}, or None.

  • write_parameters (dict[str, Any] | None) – Extra arguments passed to the model when embedding an upsert, e.g. {"input_type": "passage"}, or None.

Parameters:
model: str
metric: str | None
description: str | None
read_parameters: dict[str, Any] | None
write_parameters: dict[str, Any] | None
class pinecone.models.indexes.schema.StringField(*, description=None, filterable=False, full_text_search=None)[source]

Bases: Struct

Text, either full-text searchable or filterable — never both.

A string field you declare on create must carry a full_text_search config, because search is the only reason the schema takes a string field. Text you only want to filter on is not declared at all: put it in the documents you upsert. Its type in a schema= dict is "string".

In responses, a searchable field reports its full_text_search object and a filter-only field reports just filterable.

Variables:
  • description (str | None) – Free-text note about the field, or None.

  • filterable (bool) – Whether the field can be used in metadata filters. Defaults to False. Sending filterable=True alongside full_text_search does not give you both: the server keeps the filter, discards the search configuration, and reports no error for doing so, so the field silently comes back unsearchable.

  • full_text_search (pinecone.models.indexes.schema.FullTextSearchConfig | None) – A FullTextSearchConfig — its presence, even empty, is what makes the field searchable; None means it is not.

Parameters:

Examples

The schema= entry that declares one:

{"title": {"type": "string", "full_text_search": {}}}
description: str | None
filterable: bool
class pinecone.models.indexes.schema.StringListField(*, description=None, filterable=False)[source]

Bases: Struct

Tag-style metadata: a list of strings, filterable per element.

A filter on this field matches if any element matches, which is what makes it right for tags like ["sci-fi", "mystery"].

Response-only. You read one back for a field the server indexed for you at upsert time; sending string_list in a schema= on create is rejected, and one rejected field fails the whole schema. Upsert the list as an ordinary document value instead.

Variables:
  • description (str | None) – Free-text note about the field, or None.

  • filterable (bool) – Whether the field can be used in metadata filters.

Parameters:
  • description (str | None)

  • filterable (bool)

description: str | None
filterable: bool
class pinecone.models.indexes.schema.BooleanField(*, description=None, filterable=False)[source]

Bases: Struct

Boolean metadata, filterable.

Response-only. You read one back for a field the server indexed for you at upsert time; sending boolean in a schema= on create is rejected, and one rejected field fails the whole schema. Upsert the value as an ordinary document value instead.

Variables:
  • description (str | None) – Free-text note about the field, or None.

  • filterable (bool) – Whether the field can be used in metadata filters.

Parameters:
  • description (str | None)

  • filterable (bool)

description: str | None
filterable: bool
class pinecone.models.indexes.schema.IntegerField(*, description=None, filterable=False)[source]

Bases: Struct

Integer metadata on an index that predates numeric normalisation.

Response-only, and the one field type with a sharp edge. Numbers are normalised to float at upsert time now, so integer only ever comes back from an older index. There is no integer type in the create schema, and sending one is rejected with a plain-text body rather than a structured API error — so the exception you catch will not tell you which field was at fault.

This matters for describe-then-create: a schema read off an old index cannot be handed straight to create. Drop its integer fields, since numeric metadata is indexed for filtering automatically at upsert time. SchemaBuilder has no method for this type and refuses {"type": "integer"} passed through add_custom_field(), so building the schema that way fails client-side with an explanation instead.

Variables:
  • description (str | None) – Free-text note about the field, or None.

  • filterable (bool) – Whether the field can be used in metadata filters.

Parameters:
  • description (str | None)

  • filterable (bool)

description: str | None
filterable: bool
class pinecone.models.indexes.schema.FloatField(*, description=None, filterable=False)[source]

Bases: Struct

Numeric metadata, filterable and range-comparable.

Double-precision throughout, which is why range filters like year >= 2020 work on it and why there is no separate integer type: integers are stored and filtered as floats, and float is the only numeric type name the API uses.

Response-only. You read one back for a field the server indexed for you at upsert time; sending float in a schema= on create is rejected, and one rejected field fails the whole schema. Upsert the number as an ordinary document value instead.

Variables:
  • description (str | None) – Free-text note about the field, or None.

  • filterable (bool) – Whether the field can be used in metadata filters.

Parameters:
  • description (str | None)

  • filterable (bool)

description: str | None
filterable: bool
class pinecone.models.indexes.schema.LegacyMetadataField(*, filterable)[source]

Bases: Struct

A metadata field from an index older than typed schemas.

These fields carry no type at all on the wire, and their original data type was never recorded, so filterable is all there is to read. New indexes never produce one.

Variables:

filterable (bool) – Whether the field is indexed for metadata filtering.

Parameters:

filterable (bool)

Note

Decoding a union needs a discriminator, so instances carry the internal tag "__untyped__". IndexSchema.to_dict() strips it and it never reaches the API, but msgspec.json.encode of this class does emit it.

filterable: bool
class pinecone.models.indexes.schema.FullTextSearchConfig(*, language=None, stemming=None, stop_words=None, ngram=None)[source]

Bases: Struct

How a string field’s text is analysed for full-text search.

Its presence on a StringField is what makes the field full-text searchable at all; None means it is not. Every key is optional, so an empty FullTextSearchConfig() is a valid way to say “searchable, server defaults please”. Responses always report language, stemming and stop_words as resolved values.

Variables:
  • language (str | None) – Language whose analysis rules to use, as a two-letter code or its English name — "en" and "english" are both accepted. None takes the server default of English.

  • stemming (bool | None) – Fold tokens to their root form, so running matches run. None takes the server default of off.

  • stop_words (bool | None) – Drop common words like the from the index. Requires stemming=True, and is not supported for every language — the rejection names the unsupported language by its English name rather than the code you sent. None takes the server default of off.

  • ngram (pinecone.models.indexes.schema.NgramConfig | None) – A NgramConfig to index character runs instead of words, or None for word tokenization. Mutually exclusive with stemming and stop_words.

Parameters:
language: str | None
stemming: bool | None
stop_words: bool | None
ngram: NgramConfig | None
class pinecone.models.indexes.schema.NgramConfig(*, min_gram, max_gram, prefix_only=False)[source]

Bases: Struct

Tokenize a string field into character n-grams instead of words.

Word tokenization matches whole words, so a search for head misses headphones. N-gram tokenization indexes runs of characters instead, which is what makes substring matching and autocomplete work. It cannot be combined with stemming or stop_words.

Variables:
  • min_gram (int) – Shortest run of characters to index. The shorter this is, the more aggressively short queries match.

  • max_gram (int) – Longest run of characters to index; no smaller than min_gram.

  • prefix_only (bool) – When True, index only the runs anchored at the start of the token, which is what autocomplete wants. Defaults to False.

Parameters:
  • min_gram (int)

  • max_gram (int)

  • prefix_only (bool)

Examples

Substring matching on a product title:

{"title": {"type": "string", "full_text_search": {
    "ngram": {"min_gram": 2, "max_gram": 3}}}}
min_gram: int
max_gram: int
prefix_only: bool

Index Deployment Models

IndexModel.deployment describes where and how the index runs. These types replace IndexSpec, ServerlessSpecInfo, PodSpecInfo and ByocSpecInfo, which survive only as the deprecated views above.

pinecone.models.indexes.deployment.IndexDeployment = pinecone.models.indexes.deployment.ManagedDeployment | pinecone.models.indexes.deployment.PodDeployment | pinecone.models.indexes.deployment.ByocDeployment

The three deployment variants, told apart by their deployment_type. Narrow an IndexModel.deployment with isinstance before reading fields only one variant has.

class pinecone.models.indexes.deployment.ManagedDeployment(*, cloud, region, environment=None)[source]

Bases: Struct

A serverless index: Pinecone picks the capacity, you pick the region.

The default deployment, and what to reach for unless you have a reason not to — no replicas or shards to size, and full-text search indexes run here too. Its deployment_type is "managed".

Variables:
  • cloud (str) – Public cloud to run in — "aws", "gcp", or "azure". See CloudProvider.

  • region (str) – Region within that cloud, e.g. "us-east-1".

  • environment (str | None) – The internal cell hosting the index, derived from cloud and region. Response-only and informational; you cannot set it, and it is not something to build on.

Parameters:
  • cloud (str)

  • region (str)

  • environment (str | None)

Examples

The deployment= argument that asks for one:

{"deployment_type": "managed", "cloud": "aws", "region": "us-east-1"}
cloud: str
region: str
environment: str | None
class pinecone.models.indexes.deployment.PodDeployment(*, environment, pod_type, replicas, shards)[source]

Bases: Struct

A pod-based index: you size the hardware yourself.

The older deployment model, where capacity is something you choose and pay for rather than something that scales. Its deployment_type is "pod". Every attribute below is required on create — leaving out replicas or shards is rejected — and every one comes back on a describe.

Variables:
  • environment (str) – The environment hosting the index, which stands in for a cloud and region pair, e.g. "us-east1-gcp". See PodIndexEnvironment.

  • pod_type (str) – Hardware family and size, e.g. "p1.x1". See PodType.

  • replicas (int) – How many copies of the index to run. More replicas mean more query throughput and more availability, at proportional cost. One of the two things configure can change later, along with pod_type.

  • shards (int) – How many pods to split the data across, which is what decides how much data fits. Fixed once the index exists.

Parameters:
  • environment (str)

  • pod_type (str)

  • replicas (int)

  • shards (int)

environment: str
pod_type: str
replicas: int
shards: int
class pinecone.models.indexes.deployment.ByocDeployment(*, environment)[source]

Bases: Struct

A BYOC index: Pinecone’s data plane, running in your own account.

Bring-your-own-compute indexes run in infrastructure you operate, so the only thing to name is the environment Pinecone provisioned there. Its deployment_type is "byoc".

Variables:

environment (str) – The BYOC environment to run in, e.g. "aws-us-east-1-b921". Pinecone gives you this identifier when the environment is set up.

Parameters:

environment (str)

environment: str

Read Capacity Models

IndexModel.read_capacity replaces the removed IndexSpec.serverless.read_capacity.

pinecone.models.indexes.read_capacity.ReadCapacityResponse = pinecone.models.indexes.read_capacity.ReadCapacityOnDemandResponse | pinecone.models.indexes.read_capacity.ReadCapacityDedicatedResponse

The two read-capacity variants, told apart by their mode. Narrow an IndexModel.read_capacity with isinstance before reading dedicated, which only one variant has.

class pinecone.models.indexes.read_capacity.ReadCapacityOnDemandResponse(*, status)[source]

Bases: Struct

Read capacity that scales with traffic and bills per read.

The default, and the one with nothing to size: reads bill per operation, so there is no configuration to read back — only a status. Its mode is "OnDemand". Reach for ReadCapacityDedicatedResponse when you want to control the shards and replicas serving reads instead; see How Pinecone Works.

Variables:

status (pinecone.models.indexes.read_capacity.ReadCapacityStatus) – A ReadCapacityStatus.

Parameters:

status (ReadCapacityStatus)

status: ReadCapacityStatus
class pinecone.models.indexes.read_capacity.ReadCapacityDedicatedResponse(*, dedicated, status)[source]

Bases: Struct

Read capacity served by nodes provisioned for this index alone.

Its mode is "Dedicated", and unlike on-demand it reports the hardware behind it, because you chose it. Changing the counts puts status.state into "Scaling" until the new shape is in place.

Variables:
Parameters:
dedicated: ReadCapacityDedicatedConfig
status: ReadCapacityStatus
class pinecone.models.indexes.read_capacity.ReadCapacityDedicatedConfig(*, node_type, scaling, manual=None)[source]

Bases: Struct

What the dedicated read tier is made of.

Variables:
Parameters:
node_type: str
scaling: str
manual: ScalingConfigManual | None
class pinecone.models.indexes.read_capacity.ReadCapacityStatus(*, state, current_shards=None, current_replicas=None, error_message=None)[source]

Bases: Struct

Whether an index’s read capacity is provisioned and serving.

Separate from IndexStatus: an index can be ready while its read tier is still scaling into place.

Variables:
  • state (str) – Where provisioning is — "Ready" most of the time, "Scaling" after a recent replica or shard change, "Migrating" while moving to a new node type, or "Error", in which case read error_message.

  • current_shards (int | None) – Current number of active shards. None for an index with on-demand read capacity, which has no fixed shard count.

  • current_replicas (int | None) – Current number of active replicas. None for an index with on-demand read capacity, which has no fixed replica count.

  • error_message (str | None) – Message describing a read-capacity configuration issue; None unless state is "Error".

Parameters:
  • state (str)

  • current_shards (int | None)

  • current_replicas (int | None)

  • error_message (str | None)

state: str
current_shards: int | None
current_replicas: int | None
error_message: str | None
class pinecone.models.indexes.read_capacity.ScalingConfigManual(*, shards, replicas)[source]

Bases: Struct

The shard and replica counts you chose for dedicated read capacity.

Present when scaling is "Manual" — you are sizing the read side yourself rather than letting Pinecone size it.

Variables:
  • shards (int) – How many shards to split reads across, which is what decides how much data the read tier holds.

  • replicas (int) – How many copies of each shard to run, which is what decides read throughput. 0 is legal and stops the index serving reads entirely — a way to pause the cost of an index you are not querying without deleting it.

Parameters:
shards: int
replicas: int

Vector Models

class pinecone.models.vectors.vector.Vector(id, values=<factory>, sparse_values=None, metadata=None)[source]

Bases: DictLikeStruct, Struct

One record in a vector-based index: an ID, its coordinates, and its metadata.

A vector carries its coordinates in either or both of two representations, and which ones you populate is what makes a vector dense, sparse, or hybrid:

  • Densevalues, a list of floats whose length equals the dimension of the index field it is written to, ranked by that field’s metric. This is the usual output of an embedding model, and the representation that finds records by meaning. Build a dense vector when you have an embedding.

  • Sparsesparse_values, which names only the non-zero dimensions as parallel indices and values lists and has no fixed dimension. This is how keyword-based scoring such as BM25 is expressed, and it finds records by exact term. Build a sparse vector when the terms themselves matter.

  • Hybrid — both populated on the same vector, so one record is reachable by meaning and by term. The index has to declare a dense field and a sparse field for this to be accepted.

At least one of the two must be populated. A sparse-only vector leaves values empty, and the empty dense list is still sent.

Variables:
  • id (str) – Unique identifier for the vector; the client rejects an ID that is not ASCII, is empty, is over 512 characters, or contains NUL. Use an ID you can recompute from your own data, e.g. "article-101".

  • values (list[float]) – Dense vector values. Empty for a sparse-only vector.

  • sparse_values (SparseValues | None) – Sparse component, or None for a dense-only vector.

  • metadata (dict[str, Any] | None) – Your own key-value pairs to filter on later, or None if none are attached. Each value must be a string, a number, a boolean, or a list of strings — a nested object, or a list with a non-string element, is rejected. A key whose value is None is dropped rather than rejected. Keys may not begin with $, which is reserved for filter operators; every other key is accepted, including empty and non-ASCII keys.

Raises:

PineconeValueError – If neither values nor sparse_values is populated — a vector with no coordinates cannot be scored against anything.

Parameters:

Examples

A dense vector. Pass the embedding your model produced; its length has to match the dimension of the field you upsert into, so the three floats here stand in for a full-length embedding.

>>> from pinecone import Vector
>>> dense = Vector(id="article-101", values=[0.12, 0.34, 0.56])
>>> dense.sparse_values is None
True

A sparse vector, where each index is a term slot that scored non-zero. values comes back empty because nothing dense was supplied.

>>> from pinecone import SparseValues
>>> sparse = Vector(
...     id="article-102",
...     sparse_values=SparseValues(indices=[10, 42, 913], values=[0.4, 0.9, 0.2]),
... )
>>> sparse.values
[]

A hybrid vector populates both, and can carry metadata to filter on.

>>> hybrid = Vector(
...     id="article-103",
...     values=[0.12, 0.34, 0.56],
...     sparse_values=SparseValues(indices=[10, 42], values=[0.4, 0.9]),
...     metadata={"lang": "en", "published": True},
... )
>>> len(hybrid.values), len(hybrid.sparse_values.indices)
(3, 2)

See also

ScoredVector — what a query returns for each match, which adds score. DocumentRecord — the record type for schema-based indexes, which store JSON documents rather than raw vectors.

id: str
values: list[float]
sparse_values: SparseValues | None
metadata: dict[str, Any] | None
static from_dict(vector_dict)[source]

Build a Vector from a plain dict.

Accepts the snake_case keys id, values, sparse_values and metadata. Use it when your vectors arrive as dicts — from your own JSON, a dataframe row, or a previous to_dict() — and you want the same construction-time check that Vector(...) applies.

Parameters:

vector_dict (dict[str, Any]) – The dict to convert. id is required; the rest are optional and default the same way the constructor does.

Returns:

Vector with sparse_values decoded into a SparseValues.

Raises:
Return type:

Vector

Examples

>>> from pinecone import Vector
>>> Vector.from_dict({"id": "article-101", "values": [0.12, 0.34, 0.56]}).id
'article-101'
class pinecone.models.vectors.vector.ScoredVector(*, id, score, values=<factory>, sparse_values=None, metadata=None)[source]

Bases: DictLikeStruct, Struct

One match from a query: the vector that was found, plus how close it was.

Every element of QueryResponse.matches is one of these, so id and score are always populated. values and metadata are not: a query omits both unless you ask for them, so an empty values or a None metadata usually means the request did not set the corresponding flag rather than that the stored vector lacks them.

Variables:
  • id (str) – Identifier of the matched vector, the same ID it was upserted under.

  • score (float) – How close the match is under the queried field’s metric. Higher is closer for cosine and dotproduct; lower is closer for euclidean. Compare scores only within one response — the scale depends on the metric and on your data, so no fixed threshold means “good” across indexes.

  • values (list[float]) – Dense values of the matched vector, or [] when the query did not pass include_values=True.

  • sparse_values (SparseValues | None) – Sparse component of the matched vector, or None for a dense-only vector or when values were not requested.

  • metadata (dict[str, Any] | None) – The metadata stored with the vector, or None when the query did not pass include_metadata=True or nothing was stored. Values follow the same grammar as Vector.metadata.

Parameters:

Examples

A query returns these in matches, ordered most similar first, so reading a result is the same two attributes every time.

response = idx.query(top_k=5, vector=[0.012, -0.087, 0.153])
for match in response.matches:
    print(match.id, match.score)

Ask for metadata if you intend to read it — without the flag match.metadata is None even for vectors that have metadata stored.

response = idx.query(
    top_k=5,
    vector=[0.012, -0.087, 0.153],
    namespace="articles-en",
    include_metadata=True,
)
for match in response.matches:
    print(match.id, match.metadata["lang"])
id: str
score: float
values: list[float]
sparse_values: SparseValues | None
metadata: dict[str, Any] | None
class pinecone.models.vectors.sparse.SparseValues(indices, values)[source]

Bases: DictLikeStruct, Struct

A sparse vector, given as its non-zero dimensions and their weights.

A dense vector lists a float for every dimension; a sparse vector lists only the dimensions that are not zero, as two parallel lists of the same length. Sparse vectors have no declared dimension, so any index is legal and two sparse vectors in the same field need not name the same ones. Use one wherever a sparse component is asked for: Vector.sparse_values when upserting, and the sparse_vector argument when querying.

Variables:
  • indices (list[int]) – The dimensions that carry a weight, typically the term slots a sparse embedding model or BM25 encoder produced.

  • values (list[float]) – The weight for each entry of indices, positionally. The two lists must be the same length.

Parameters:

Examples

>>> from pinecone import SparseValues
>>> sparse = SparseValues(indices=[10, 42, 913], values=[0.4, 0.9, 0.2])
>>> dict(zip(sparse.indices, sparse.values))
{10: 0.4, 42: 0.9, 913: 0.2}
indices: list[int]
values: list[float]
static from_dict(sparse_values_dict)[source]

Build a SparseValues from a plain dict.

Parameters:

sparse_values_dict (dict[str, Any]) – Dict with indices and values keys, both required.

Returns:

SparseValues carrying those two lists.

Raises:

KeyError – If either indices or values is absent.

Return type:

SparseValues

Examples

>>> from pinecone import SparseValues
>>> SparseValues.from_dict({"indices": [10, 42], "values": [0.4, 0.9]}).indices
[10, 42]
class pinecone.models.vectors.usage.Usage(*, read_units=None, write_units=None)[source]

Bases: Struct

What one data-plane call cost, in read and write units.

Reachable as usage on the read responses — QueryResponse, FetchResponse, ListResponse — where it is the per-call figure, not a running total. Only one side is normally populated: a read reports read_units and leaves write_units as None.

Variables:
  • read_units (int | None) – Read units this call consumed, or None when the operation does not report them.

  • write_units (int | None) – Write units this call consumed, or None when the operation does not report them.

Parameters:
  • read_units (int | None)

  • write_units (int | None)

read_units: int | None
write_units: int | None
class pinecone.models.vectors.responses.QueryResponse(*, matches=<factory>, namespace='', usage=None, response_info=None)[source]

Bases: DictLikeStruct, Struct

The ranked matches a query found.

Almost everything you want is in matches: a list of ScoredVector, already ordered so matches[0] is the closest hit. Read each match through .id, .score, .values and .metadata. The last two come back empty or None unless the query passed include_values=True / include_metadata=True, so a missing value there is far more often an unset flag than an empty stored vector.

A query that matched nothing returns an empty matches rather than raising, so check the length instead of catching an exception.

Variables:
  • matches (list[ScoredVector]) – The hits, ordered from most to least similar.

  • namespace (str) – The namespace that was queried; "" for the default namespace.

  • usage (Usage | None) – Read units this query consumed, or None if not reported.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

response = idx.query(
    top_k=5,
    vector=[0.012, -0.087, 0.153],
    namespace="articles-en",
    include_metadata=True,
)
for match in response.matches:
    print(match.id, match.score, match.metadata)

No match is not an error:

if not response.matches:
    print("nothing above the cutoff in", response.namespace)

See also

SearchRecordsResponse — what search returns instead, where the hits sit under result.hits and carry fields rather than values and metadata.

matches: list[ScoredVector]
namespace: str | None
usage: Usage | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.FetchResponse(*, vectors=<factory>, namespace='', usage=None, response_info=None)[source]

Bases: DictLikeStruct, Struct

The vectors a fetch retrieved, keyed by ID.

vectors is a dict, not a list, so look a vector up by the ID you asked for. An ID that does not exist in the namespace is simply absent from the dict — fetching a missing ID is not an error — so use .get() or test membership rather than indexing blind. Unlike a query, a fetch always returns values and metadata; there is nothing to opt into.

Variables:
  • vectors (dict[str, Vector]) – Vector ID to Vector, for the requested IDs that exist.

  • namespace (str) – The namespace the vectors were fetched from.

  • usage (Usage | None) – Read units this fetch consumed, or None if not reported.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

wanted = ["article-101", "article-102"]
response = idx.fetch(ids=wanted, namespace="articles-en")
for vector_id, vector in response.vectors.items():
    print(vector_id, len(vector.values), vector.metadata)
print("not stored:", [vid for vid in wanted if vid not in response.vectors])

See also

FetchByMetadataResponse — what you get when you select the vectors by metadata filter rather than by ID, which can span more than one page.

vectors: dict[str, Vector]
namespace: str
usage: Usage | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.FetchByMetadataResponse(*, vectors=<factory>, namespace='', usage=None, pagination=None, response_info=None)[source]

Bases: DictLikeStruct, Struct

One page of the vectors matching a metadata filter, keyed by ID.

Same shape as FetchResponse plus pagination: a filter can match more vectors than one response carries, so this is a page and not the whole answer. Keep calling with the token until pagination is None.

Variables:
  • vectors (dict[str, Vector]) – Vector ID to Vector for the matches on this page.

  • namespace (str) – The namespace the vectors were fetched from.

  • usage (Usage | None) – Read units this page consumed, or None if not reported.

  • pagination (Pagination | None) – Token to pass as pagination_token for the next page, or None when this is the last page.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

token = None
while True:
    page = idx.fetch_by_metadata(
        filter={"lang": "en"}, namespace="articles-en", pagination_token=token
    )
    for vector_id, vector in page.vectors.items():
        print(vector_id, vector.metadata)
    if page.pagination is None:
        break
    token = page.pagination.next

See also

Pagination — the paging pattern used across the SDK.

vectors: dict[str, Vector]
namespace: str
usage: Usage | None
pagination: Pagination | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.UpsertResponse(*, upserted_count, response_info=None, total_item_count=0, failed_item_count=0, total_batch_count=0, successful_batch_count=0, failed_batch_count=0, errors=<factory>)[source]

Bases: DictLikeStruct, Struct

What an upsert wrote, and — for a batched upsert — what it failed to write.

Which fields carry information depends on how you called upsert. Without batch_size the client sends one request, so upserted_count is the whole answer and every batch counter is 0. With batch_size the client splits the vectors into requests and sends them one at a time; a later request can fail after earlier ones succeeded, so the batch counters and errors describe a partial success and upserted_count covers only the batches that landed.

Variables:
  • upserted_count (int) – Vectors the server accepted. Equals total_item_count when every batch succeeded, and for a non-batched call.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

  • total_item_count (int) – Vectors you submitted, across every batch. 0 for a non-batched call.

  • failed_item_count (int) – Vectors that were in a batch that failed. Not all of them were necessarily rejected individually — the batch is the unit.

  • total_batch_count (int) – Batches the client sent. 0 for a non-batched call.

  • successful_batch_count (int) – Batches the server accepted.

  • failed_batch_count (int) – Batches that failed.

  • errors (list[BatchError]) – One entry per failed batch, carrying the underlying error and the items that batch held. Empty when nothing failed.

Parameters:

Examples

A single upsert reports one number.

response = idx.upsert(vectors=[("article-101", [0.12, 0.34, 0.56])])
print(response.upserted_count)

A batched upsert can partly succeed, so check has_errors before treating upserted_count as the full count. failed_items flattens the items from every failed batch back into a list you can resubmit.

response = idx.upsert(vectors=vectors, batch_size=100)
if response.has_errors:
    print(response.upserted_count, "of", response.total_item_count)
    retry = idx.upsert(vectors=response.failed_items, batch_size=100)

See also

Performance — choosing a batch_size.

upserted_count: int
response_info: ResponseInfo | None
total_item_count: int
failed_item_count: int
total_batch_count: int
successful_batch_count: int
failed_batch_count: int
errors: list[BatchError]
property has_errors: bool

True if any batch failed, so upserted_count is a partial count.

property error_count: int

Alias for failed_item_count, spelled as BatchResult spells it.

property success_count: int

Alias for upserted_count, spelled as BatchResult spells it.

property successful_item_count: int

Alias for upserted_count, spelled as BatchResult spells it.

property failed_items: list[dict[str, Any]]

Every item from every failed batch, flattened into one list you can resubmit.

Empty when has_errors is False. Items that were in a successful batch are never included, so passing this straight back to upsert retries only the writes that did not land.

class pinecone.models.vectors.responses.UpdateResponse(*, matched_records=None, response_info=None)[source]

Bases: DictLikeStruct, Struct

Acknowledgement that an update was accepted, and how many vectors it matched.

Variables:
  • matched_records (int | None) – Vectors the update matched, or None when no count was reported. A by-filter update is the case that reports one; pass dry_run=True to get the count without applying the change. Updates apply asynchronously, so a count here is a point-in-time figure rather than a guarantee that the writes have landed.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:
matched_records: int | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.ListResponse(*, vectors=<factory>, pagination=None, namespace='', usage=None, response_info=None)[source]

Bases: StructDictMixin, Struct

One page of vector IDs from a namespace.

Each element of vectors is a ListItem carrying only an id. The response is also directly iterable and sized, so for item in response and len(response) walk that same page.

Variables:
  • vectors (list[ListItem]) – The ID entries on this page.

  • pagination (Pagination | None) – Token for the next page, or None when this is the last page.

  • namespace (str) – The namespace the IDs were listed from.

  • usage (Usage | None) – Read units this page consumed, or None if not reported.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

page = idx.list_paginated(prefix="article-", namespace="articles-en")
for item in page.vectors:
    print(item.id)

See also

Pagination — and Index.list, which yields every page for you.

vectors: list[ListItem]
pagination: Pagination | None
namespace: str
usage: Usage | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.ListItem(*, id=None)[source]

Bases: StructDictMixin, Struct

One entry in ListResponse.vectors — an ID and nothing else.

list walks the IDs in a namespace without reading the vectors themselves, so there are no values or metadata here. Fetch the IDs you care about to get those.

Variables:

id (str | None) – The vector identifier, or None if the entry carried none.

Parameters:

id (str | None)

id: str | None
class pinecone.models.vectors.responses.Pagination(*, next=None)[source]

Bases: StructDictMixin, Struct

The cursor that carries you from one page of results to the next.

Appears as pagination on every paged response. A None on the response, or a None in next, both mean the page you are holding is the last one — that is the loop’s exit condition, not an error.

Variables:

next (str | None) – Opaque token to pass back as the next call’s pagination_token, or None when there is no further page. Treat it as opaque: it is not an ID, an offset, or anything you can construct yourself.

Parameters:

next (str | None)

See also

Pagination — the paging loop, and the paginated helpers that run it for you.

next: str | None
class pinecone.models.vectors.responses.DescribeIndexStatsResponse(*, namespaces=<factory>, dimension=None, index_fullness=0.0, total_vector_count=0, metric=None, vector_type=None, memory_fullness=None, storage_fullness=None, response_info=None)[source]

Bases: StructDictMixin, Struct

How much is in an index, and how it is configured, as of this call.

The usual reason to call describe_index_stats is to find out which namespaces exist and how many vectors each holds — namespaces answers both, and its keys are the namespace names you can pass to a query. Counts are eventually consistent, so a vector you just upserted may not be reflected yet.

Variables:
  • namespaces (dict[str, NamespaceSummary]) – Namespace name to its NamespaceSummary. The default namespace appears under "".

  • dimension (int | None) – Length of the dense vectors this index stores, or None for an index with no dense field.

  • index_fullness (float) – How full the index is, from 0.0 to 1.0.

  • total_vector_count (int) – Vectors across every namespace.

  • metric (str | None) – The similarity function used when ranking, e.g. "cosine", or None if not reported.

  • vector_type (str | None) – "dense" or "sparse", or None if not reported.

  • memory_fullness (float | None) – How full memory is, or None if not reported.

  • storage_fullness (float | None) – How full storage is, or None if not reported.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

stats = idx.describe_index_stats()
print(stats.total_vector_count, stats.dimension)
for name, summary in stats.namespaces.items():
    print(name or "(default)", summary.vector_count)
namespaces: dict[str, NamespaceSummary]
dimension: int | None
index_fullness: float
total_vector_count: int
metric: str | None
vector_type: str | None
memory_fullness: float | None
storage_fullness: float | None
response_info: ResponseInfo | None
class pinecone.models.vectors.responses.NamespaceSummary(*, vector_count=0)[source]

Bases: StructDictMixin, Struct

The per-namespace entry in DescribeIndexStatsResponse.

Variables:

vector_count (int) – Vectors in this namespace.

Parameters:

vector_count (int)

vector_count: int
class pinecone.models.vectors.responses.UpsertRecordsResponse(*, record_count, response_info=None)[source]

Bases: StructDictMixin, Struct

Acknowledgement that upsert_records was accepted.

upsert_records embeds text server-side and the response body carries no counts, so record_count is what the client sent rather than what the server confirmed. Read it as “the request went out with this many records”, and call describe_index_stats if you need a count the index vouches for.

Variables:
  • record_count (int) – Records the client submitted. A client-side count.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:
record_count: int
response_info: ResponseInfo | None
class pinecone.models.response_info.BatchResponseInfo(*, lsn_reconciled=None, lsn_committed=None)[source]

Bases: StructDictMixin, Struct

The same durability signal as ResponseInfo, for a whole batch.

A bulk method makes many requests, each with its own headers, and reports one of these as its result’s response_info. It keeps the highest log position any successful sub-request reported, which is the position the whole batch is durable through.

It has no raw_headers and no request_id: there is no single response to point at. When a sub-batch failed, its own exception is on that failure’s error attribute in the result’s errors list.

Variables:
  • lsn_reconciled (int | None) – Highest reconciled position any successful sub-request reported, or None when none reported one.

  • lsn_committed (int | None) – Highest committed position any successful sub-request reported, or None when none reported one. Keep it to check a later read against.

Parameters:
  • lsn_reconciled (int | None)

  • lsn_committed (int | None)

Examples

Keep the position a bulk write reached, to check a later read against:

index = pc.index(name="product-search")
result = index.documents.batch_upsert(
    namespace="published",
    documents=[
        {"_id": f"article-{i:05d}", "chunk_text": f"Paragraph {i}"}
        for i in range(500)
    ],
)
target = None
if result.response_info is not None:
    target = result.response_info.lsn_committed
lsn_reconciled: int | None
lsn_committed: int | None
is_reconciled(target)[source]

Has every successful sub-request caught up to target?

The batch equivalent of ResponseInfo.is_reconciled(), answered from the highest position any sub-request reported.

Parameters:

target (int)

Return type:

bool

class pinecone.models.response_info.ResponseInfo(*, raw_headers=<factory>)[source]

Bases: StructDictMixin, Struct

What the server said about a data-plane call, beyond the result itself.

Every data-plane response carries one as response_info, and there are two reasons to reach for it. request_id is what a Pinecone support conversation asks you for. The two LSN properties are how you check read-your-writes: an upsert reports the log position it committed at, and a later read reports how far the index has caught up, so you can tell whether a query was allowed to see your write yet.

Reads are eventually consistent, so a query issued immediately after a write can legitimately miss it. is_reconciled() is the check that turns that from a guess into an answer.

Variables:
  • raw_headers (dict[str, str]) – All HTTP response headers, keys normalized to lowercase. Defaults to an empty dict. Use this to read any header the server returns, including headers not surfaced by the typed properties below. Prefer the typed properties when available — wire header names may change, but property semantics are stable.

  • request_id (str | None) – Identifier the server assigned this request. Quote it when reporting a problem. None when the header is absent.

  • lsn_reconciled (int | None) – How far the index has caught up, as a log position. None when the header is absent, so a None here means unknown, not position zero.

  • lsn_committed (int | None) – Log position this write landed at. None when the header is absent — including on reads, which commit nothing.

Parameters:

raw_headers (dict[str, str])

Examples

Write, then read back only once the index has caught up to the write:

import time

index = pc.index(name="product-search")
written = index.documents.upsert(
    namespace="published",
    documents=[{"_id": "article-00042", "chunk_text": "Q3 revenue"}],
)
target = written.response_info.lsn_committed

while True:
    fetched = index.documents.fetch(
        namespace="published", ids=["article-00042"]
    )
    if target is None or fetched.response_info.is_reconciled(target):
        break
    time.sleep(0.5)

See also

BatchResponseInfo — the same durability signal for a bulk method, aggregated over the requests it made.

raw_headers: dict[str, str]
property request_id: str | None

Identifier the server assigned this request.

The one field worth logging on every call: it is what a Pinecone support conversation asks for, and the only handle on a single request after the fact.

Returns:

The request ID, or None when the server sent no such header.

property lsn_reconciled: int | None

How far the index has caught up, as a log position.

Compare it against a lsn_committed from an earlier write to find out whether that write is visible yet; is_reconciled() does the comparison for you.

Returns:

The reconciled position, or None when the header is absent or not an integer. None means unknown, not position zero, so never treat it as “nothing reconciled”.

property lsn_committed: int | None

Log position the write on this response landed at.

Keep it from an upsert or delete response and pass it to is_reconciled() on a later read to check that the read saw the write.

Returns:

The committed position, or None when the header is absent or not an integer — including on a read, which commits nothing.

is_reconciled(target)[source]

Has this response’s index caught up to target yet?

The read-your-writes check: pass the lsn_committed from an earlier write and get back whether the read that produced this response was able to see it.

A False means “not yet, as of this response” — it is a reason to read again, not an error. False is also what you get when this response carried no reconciled position at all, since an unknown position cannot be shown to have caught up.

Parameters:

target (int) – Log position to compare against, normally the lsn_committed of a prior upsert or delete. Guard against that being None before calling.

Returns:

True when lsn_reconciled is known and at least target; False otherwise.

Return type:

bool

Batch Models

index.documents.batch_upsert returns a BatchResult, which collects per-batch failures instead of raising on the first one.

class pinecone.models.batch.BatchResult(*, total_item_count, successful_item_count, failed_item_count, total_batch_count, successful_batch_count, failed_batch_count, errors, response_info=None, timed_out=False, throttle_event_count=0, final_limit=None, peak_inflight=0, stalled=False)[source]

Bases: Struct

What a bulk method returns instead of raising.

A bulk method splits your items into batches and reports the outcome of all of them here, so a partial failure is a value you inspect rather than an exception that loses the successes. Start with has_errors; if it is True, errors holds one BatchError per failed batch, each carrying its own items back.

The last five attributes are backpressure telemetry rather than results. Read them when a bulk write was slower than expected: they say whether the backend was throttling you, and whether the SDK gave up on it.

Variables:
  • total_item_count (int) – How many items you passed in.

  • successful_item_count (int) – How many were in batches that landed.

  • failed_item_count (int) – How many were in batches that did not.

  • total_batch_count (int) – How many batches the items were split into.

  • successful_batch_count (int) – How many of those landed.

  • failed_batch_count (int) – How many did not.

  • errors (list[pinecone.models.batch.BatchError]) – One BatchError per failed batch.

  • response_info (pinecone.models.response_info.BatchResponseInfo | None) – A BatchResponseInfo carrying the log position the batch is durable through, or None when no batch reported one. Use it to check that a later read sees these writes.

  • timed_out (bool) – Whether a total_timeout expired with work left unsent. The batches that were never attempted appear in errors, so failed_items is what remains to be sent. A deadline that elapses while the last batches are in flight, all of which then land, does not set this — there would be nothing to retry.

  • throttle_event_count (int) – Throttle signals the host’s adaptive gate heard during this operation. Host-level, not call-level: concurrent operations against the same host share the gate, so their throttles are counted here too.

  • final_limit (int | None) – The adaptive concurrency limit when this operation finished, or None when the operation did not run through the gate. A value far below your max_concurrency means the backend was pushing back.

  • peak_inflight (int) – The most batches this operation had in flight at once.

  • stalled (bool) – Whether the host gate’s stall detector fired during this operation — the adaptive limit was at the floor with consecutive all-failed settles, so the remainder was abandoned rather than queued against an apparently-dead backend. Abandoned batches appear in errors with disposition="abandoned"; the gate itself re-probes after a cool-down.

Parameters:

Examples

>>> index = pc.index(name="product-search")
>>> documents = [
...     {"_id": f"article-{i:05d}", "chunk_text": f"Paragraph {i}"}
...     for i in range(1000)
... ]
>>> result = index.documents.batch_upsert(
...     namespace="published", documents=documents
... )
>>> result.successful_item_count, result.has_errors
(1000, False)

Resend only the batches a retry could actually help, which is not the same set as failed_items:

worth_retrying = [
    item
    for error in result.errors
    if error.retryable
    for item in error.items
]
if worth_retrying:
    index.documents.batch_upsert(
        namespace="published", documents=worth_retrying
    )
total_item_count: int
successful_item_count: int
failed_item_count: int
total_batch_count: int
successful_batch_count: int
failed_batch_count: int
errors: list[BatchError]
response_info: BatchResponseInfo | None
timed_out: bool
throttle_event_count: int
final_limit: int | None
peak_inflight: int
stalled: bool
property has_errors: bool

Whether any batch failed — the first thing to check on a result.

property error_count: int

Alias for failed_item_count; counts items, not batches.

property success_count: int

Alias for successful_item_count; counts items, not batches.

property failed_items: list[dict[str, Any]]

Every item from every failed batch, flattened into one list.

Convenient to resend, but it includes batches whose BatchError.retryable is False — those fail identically on every attempt. Filter errors on that flag instead when the retry is in a loop.

Returns:

A flat list of the items that did not land.

to_dict()[source]

Return the whole result as nested plain dicts, for logging or JSON.

Each failure’s error becomes str(error), since an exception is not serializable.

Return type:

dict[str, Any]

to_json()[source]

Return the whole result as a JSON string, with errors stringified.

Return type:

str

class pinecone.models.batch.BatchError(*, batch_index, items, error, error_message, disposition='rejected', retryable=True)[source]

Bases: Struct

One batch that did not land, and everything needed to retry it.

A bulk method captures per-batch failures instead of raising, so one bad batch does not abandon the rest. Every failure arrives as one of these in BatchResult.errors, still holding its own items.

Check retryable before resending anything: a deterministic failure resent unchanged fails again, and a retry loop that ignores the flag spins forever on it.

Variables:
  • batch_index (int) – Where this batch sat in the list you passed, counting from zero.

  • items (list[dict[str, Any]]) – The items this batch was carrying, ready to be resent.

  • error (Exception) – The exception that ended the attempt — the thing to log or re-raise when you want the underlying cause.

  • error_message (str) – The same failure as a readable string, which is what BatchResult groups and counts by.

  • disposition (str) – How far this batch got before failing, which is what tells you whether a retry could double-write. "rejected" means the attempt reached the server and came back with an error, so the write may have landed anyway; "unsent" means a deadline expired before it was submitted; "abandoned" means the backend looked down and the rest of the operation was dropped without sending. Treat the set as open — match the values you care about and let the rest fall through, because new ones can appear in a minor release.

  • retryable (bool) – Whether resending these items could plausibly work. False marks a deterministic failure — a validation error, a 4xx rejection — that would fail identically every time. Filter on it before any retry loop.

Parameters:
batch_index: int
items: list[dict[str, Any]]
error: Exception
error_message: str
disposition: str
retryable: bool
to_dict()[source]

Return the failure as a plain dict, for logging or JSON.

error becomes str(error), since an exception is not serializable; reach for the attribute itself when you need the real exception.

Return type:

dict[str, Any]

to_json()[source]

Return the failure as a JSON string, with error stringified.

Return type:

str

Search Models

class pinecone.models.vectors.search.Hit(*, id_, score_, fields=<factory>)[source]

Bases: StructDictMixin, Struct

One search result: which record matched, how well, and the fields you asked for.

Read a hit as hit.id, hit.score and hit.fields. The underscore-suffixed id_ and score_ exist because the wire names are _id and _score, which Python would name-mangle inside a class; prefer the unsuffixed properties in your own code. Bracket access works too, under the unsuffixed names: hit["id"].

fields holds your record’s own data, so what is in it depends on the fields argument the search passed — this is where a search differs from a query, which splits the same information across values and metadata.

Variables:
  • id (str) – The record identifier; read it as hit.id. Wire name _id.

  • score (float) – How well the record matched; read it as hit.score. Higher is better, and after reranking the scale is the reranker’s, not the index’s. Wire name _score.

  • fields (dict[str, Any]) – The record fields the search returned, keyed by field name. Omitting the search’s fields argument returns every field the record has, so narrow it when you only need one or two.

Parameters:

Examples

response = idx.search(
    namespace="articles-en",
    top_k=5,
    inputs={"text": "how do sparse indexes score matches"},
    fields=["title", "chunk"],
)
for hit in response.result.hits:
    print(hit.id, hit.score, hit.fields["title"])
id_: str
score_: float
fields: dict[str, Any]
property id: str

The record identifier. Prefer this over the wire-shaped id_.

property score: float

How well the record matched. Prefer this over the wire-shaped score_.

class pinecone.models.vectors.search.SearchResult(*, hits=<factory>)[source]

Bases: StructDictMixin, Struct

The one-field wrapper around a search’s hits.

It exists because the response envelope nests them, which is why reading a search result is response.result.hits and not response.hits.

Variables:

hits (list[Hit]) – The matching records, ordered best match first.

Parameters:

hits (list[Hit])

hits: list[Hit]
class pinecone.models.vectors.search.SearchRecordsResponse(*, result, usage, response_info=None)[source]

Bases: StructDictMixin, Struct

What search returns: the hits, nested one level down, plus what the call cost.

The hits live at response.result.hits — the extra result step is the shape of the response envelope, and forgetting it is the usual first stumble here. Each hit is a Hit, read as .id, .score and .fields. A search that matched nothing returns an empty hits list rather than raising.

Variables:
  • result (SearchResult) – The wrapper holding hits.

  • usage (SearchUsage) – What the search cost, broken out by stage.

  • response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or None if not populated.

Parameters:

Examples

response = idx.search(
    namespace="articles-en",
    top_k=5,
    inputs={"text": "how do sparse indexes score matches"},
    fields=["title"],
)
for hit in response.result.hits:
    print(hit.id, hit.score, hit.fields["title"])
print(response.usage.read_units)

See also

QueryResponse — what query returns instead, where the matches are at response.matches and carry values and metadata rather than fields.

result: SearchResult
usage: SearchUsage
response_info: ResponseInfo | None
class pinecone.models.vectors.search.SearchInputs[source]

Bases: dict

The inputs argument of search(), as a typed dict.

Use this when you want the index to embed your query for you rather than sending a vector — the path available on indexes with integrated inference. Like RerankConfig it is a TypedDict, so pass a plain dict and let your editor check the keys.

Variables:

text (str) – The query text to embed server-side, e.g. "how do sparse indexes score matches".

Examples

response = idx.search(
    namespace="articles-en",
    top_k=5,
    inputs={"text": "how do sparse indexes score matches"},
)
text: str
class pinecone.models.vectors.search.SearchUsage(*, read_units, embed_total_tokens=None, rerank_units=None)[source]

Bases: StructDictMixin, Struct

What one search cost, broken out by the work it did.

Which fields are populated tells you which stages ran: embed_total_tokens appears only when the index embedded your text, and rerank_units only when you passed rerank. Both being None is normal for a search that supplied its own vector.

Variables:
  • read_units (int) – Read units the search consumed.

  • embed_total_tokens (int | None) – Tokens embedded server-side, or None when the search did not embed anything.

  • rerank_units (int | None) – Rerank units consumed, or None when the search did not rerank.

Parameters:
  • read_units (int)

  • embed_total_tokens (int | None)

  • rerank_units (int | None)

read_units: int
embed_total_tokens: int | None
rerank_units: int | None
class pinecone.models.vectors.search.RerankConfig[source]

Bases: dict

The rerank argument of search(), as a typed dict.

Reranking runs a second, slower model over the hits the search already found and reorders them, which usually buys precision at the top of the list at the cost of latency. Pass this as a plain dict — it is a TypedDict, so your editor and type checker see the keys, but there is nothing to instantiate.

model and rank_fields are required; the rest are optional.

Variables:
  • model (str) – The reranking model to use, e.g. "bge-reranker-v2-m3". The model you request may not be the model that serves the request; the response reports which one did.

  • rank_fields (list[str]) – The record fields the reranker reads, e.g. ["chunk"]. These must be fields the search returns.

  • top_n (int) – How many hits to keep after reranking. Defaults to top_k, so set it lower to have the reranker narrow a wider candidate set.

  • parameters (dict[str, Any]) – Extra parameters the chosen model accepts.

  • query (str) – Text to rerank against, when it should differ from the search query — omit it and the search inputs are used.

Examples

response = idx.search(
    namespace="articles-en",
    top_k=20,
    inputs={"text": "how do sparse indexes score matches"},
    rerank={"model": "bge-reranker-v2-m3", "rank_fields": ["chunk"], "top_n": 5},
)
top_n: int
parameters: dict[str, Any]
query: str
model: str
rank_fields: list[str]
class pinecone.models.vectors.search.SearchQuery(*, inputs, top_k, filter=None, vector=None, id=None, match_terms=None)[source]

Bases: DictLikeStruct, Struct

Query parameters for a search operation (legacy backcompat type).

Variables:
  • inputs (dict[str, Any]) – Search inputs (e.g. {"text": "hello"}).

  • top_k (int) – Number of top results to return.

  • filter (dict[str, Any] | None) – Metadata filter to apply, or None for no filter.

  • vector (dict[str, Any] | None) – Explicit query vector, or None to use inputs.

  • id (str | None) – ID of a stored record to use as query vector, or None.

  • match_terms (dict[str, Any] | None) – Full-text match terms, or None.

Parameters:
inputs: dict[str, Any]
top_k: int
filter: dict[str, Any] | None
vector: dict[str, Any] | None
id: str | None
match_terms: dict[str, Any] | None
to_dict()[source]

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. Required fields (inputs, top_k) are always present; optional fields (filter, vector, id, match_terms) are omitted when they are None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchQuery
>>> query = SearchQuery(inputs={"text": "hello"}, top_k=10)
>>> query.to_dict()
{'inputs': {'text': 'hello'}, 'top_k': 10}
>>> query_with_filter = SearchQuery(
...     inputs={"text": "hello"},
...     top_k=10,
...     filter={"genre": "action"},
... )
>>> query_with_filter.to_dict()
{'inputs': {'text': 'hello'}, 'top_k': 10, 'filter': {'genre': 'action'}}
as_dict()

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. Required fields (inputs, top_k) are always present; optional fields (filter, vector, id, match_terms) are omitted when they are None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchQuery
>>> query = SearchQuery(inputs={"text": "hello"}, top_k=10)
>>> query.to_dict()
{'inputs': {'text': 'hello'}, 'top_k': 10}
>>> query_with_filter = SearchQuery(
...     inputs={"text": "hello"},
...     top_k=10,
...     filter={"genre": "action"},
... )
>>> query_with_filter.to_dict()
{'inputs': {'text': 'hello'}, 'top_k': 10, 'filter': {'genre': 'action'}}
class pinecone.models.vectors.search.SearchQueryVector(*, values=None, sparse_values=None, sparse_indices=None)[source]

Bases: DictLikeStruct, Struct

Explicit dense/sparse query vector for search operations (legacy backcompat type).

Variables:
  • values (list[float] | None) – Dense vector values, or None if not provided.

  • sparse_values (list[float] | None) – Sparse vector values, or None if not provided.

  • sparse_indices (list[int] | None) – Sparse vector indices, or None if not provided.

Parameters:
values: list[float] | None
sparse_values: list[float] | None
sparse_indices: list[int] | None
to_dict()[source]

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. All fields (values, sparse_values, sparse_indices) are optional and omitted when None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchQueryVector
>>> vec = SearchQueryVector(values=[0.1, 0.2, 0.3])
>>> vec.to_dict()
{'values': [0.1, 0.2, 0.3]}
>>> vec_sparse = SearchQueryVector(
...     values=[0.1, 0.2],
...     sparse_values=[0.5],
...     sparse_indices=[3],
... )
>>> vec_sparse.to_dict()
{'values': [0.1, 0.2], 'sparse_values': [0.5], 'sparse_indices': [3]}
as_dict()

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. All fields (values, sparse_values, sparse_indices) are optional and omitted when None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchQueryVector
>>> vec = SearchQueryVector(values=[0.1, 0.2, 0.3])
>>> vec.to_dict()
{'values': [0.1, 0.2, 0.3]}
>>> vec_sparse = SearchQueryVector(
...     values=[0.1, 0.2],
...     sparse_values=[0.5],
...     sparse_indices=[3],
... )
>>> vec_sparse.to_dict()
{'values': [0.1, 0.2], 'sparse_values': [0.5], 'sparse_indices': [3]}
class pinecone.models.vectors.search.SearchRerank(*, model, top_n=None, rank_fields=None, parameters=None, query=None)[source]

Bases: DictLikeStruct, Struct

Reranking configuration for a search operation (legacy backcompat type).

Variables:
  • model (str) – Reranking model name (e.g. "bge-reranker-v2-m3").

  • top_n (int | None) – Number of top results after reranking, or None to use top_k.

  • rank_fields (list[str] | None) – Record fields to rank on, or None.

  • parameters (dict[str, Any] | None) – Model-specific parameters, or None.

  • query (str | None) – Override query text for reranking, or None to infer from inputs.

Parameters:
model: str
top_n: int | None
rank_fields: list[str] | None
parameters: dict[str, Any] | None
query: str | None
to_dict()[source]

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. The model field is always present; optional fields (top_n, rank_fields, parameters, query) are omitted when None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchRerank
>>> rerank = SearchRerank(model="bge-reranker-v2-m3")
>>> rerank.to_dict()
{'model': 'bge-reranker-v2-m3'}
>>> rerank_full = SearchRerank(
...     model="bge-reranker-v2-m3",
...     top_n=5,
...     rank_fields=["text"],
...     query="hello world",
... )
>>> d = rerank_full.to_dict()
>>> d["model"]
'bge-reranker-v2-m3'
>>> d["top_n"]
5
>>> d["rank_fields"]
['text']
as_dict()

Return a dict of non-None field values.

Returns:

Dictionary containing only the fields whose value is not None. The model field is always present; optional fields (top_n, rank_fields, parameters, query) are omitted when None.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.vectors.search import SearchRerank
>>> rerank = SearchRerank(model="bge-reranker-v2-m3")
>>> rerank.to_dict()
{'model': 'bge-reranker-v2-m3'}
>>> rerank_full = SearchRerank(
...     model="bge-reranker-v2-m3",
...     top_n=5,
...     rank_fields=["text"],
...     query="hello world",
... )
>>> d = rerank_full.to_dict()
>>> d["model"]
'bge-reranker-v2-m3'
>>> d["top_n"]
5
>>> d["rank_fields"]
['text']
class pinecone.models.vectors.query_aggregator.QueryNamespacesResults(*, matches=<factory>, usage=<factory>, ns_usage=<factory>)[source]

Bases: StructDictMixin, Struct

One merged ranking drawn from several namespaces, as query_namespaces returns it.

Reads like a QueryResponse: matches is already interleaved and ordered, so matches[0] is the best hit found anywhere, and each element is a ScoredVector you read as .id, .score, .values and .metadata. What it does not carry is a namespace field, because the matches came from different ones — keep your own mapping from ID to namespace if you need to know where a hit lived.

Variables:
  • matches (list[ScoredVector]) – The merged top-k across every namespace queried, ordered by the metric the query named.

  • usage (Usage) – Read units summed over all the namespace queries.

  • ns_usage (dict[str, Usage]) – Read units for each namespace, keyed by namespace name, for attributing cost to one namespace rather than the fan-out.

Parameters:

Examples

results = idx.query_namespaces(
    vector=[0.012, -0.087, 0.153],
    namespaces=["articles-en", "articles-fr"],
    metric="cosine",
    top_k=5,
)
for match in results.matches:
    print(match.id, match.score)
print(results.usage.read_units, results.ns_usage)
matches: list[ScoredVector]
usage: Usage
ns_usage: dict[str, Usage]
class pinecone.models.vectors.query_aggregator.QueryResultsAggregator(*, metric, top_k=10)[source]

Bases: object

Merges per-namespace query responses into a single top-k ranking.

query_namespaces uses this internally, so reach for it directly only when you run the per-namespace queries yourself — fanning them out concurrently, or mixing in results you already had. Feed each response in with add_results(), then call get_results() once; the aggregator is single-use and refuses further input after that.

Which direction counts as “better” comes from metric, so it must match the field you queried: cosine and dotproduct rank higher scores first, euclidean ranks lower scores first. Get it wrong and you get a valid-looking ranking that is exactly backwards. Equal scores keep the order they were added in.

Parameters:
  • metric (str) – The metric the queries ranked by — "cosine", "euclidean", or "dotproduct". Keyword-only.

  • top_k (int) – How many matches to keep across all namespaces. Defaults to 10. Keyword-only.

Raises:

ValueError – If metric is not one of the three, or top_k is below 1.

Examples

>>> from pinecone.models.vectors.query_aggregator import QueryResultsAggregator
>>> from pinecone.models.vectors.responses import QueryResponse
>>> from pinecone import ScoredVector
>>> aggregator = QueryResultsAggregator(metric="cosine", top_k=2)
>>> aggregator.add_results(
...     "articles-en",
...     QueryResponse(matches=[ScoredVector(id="article-101", score=0.42)]),
... )
>>> aggregator.add_results(
...     "articles-fr",
...     QueryResponse(matches=[ScoredVector(id="article-207", score=0.91)]),
... )
>>> [match.id for match in aggregator.get_results().matches]
['article-207', 'article-101']

See also

Index.query_namespaces — the one call that fans the query out and merges for you.

__init__(*, metric, top_k=10)[source]
Parameters:
Return type:

None

add_results(namespace, response)[source]

Fold one namespace’s query response into the merge.

Call once per namespace, in any order — the ranking does not depend on the order you add them, only on the scores. Matches beyond top_k are dropped as you go, so adding many namespaces does not grow memory with the total number of matches.

Parameters:
Raises:

ValueError – If called after get_results() — the merge is closed at that point, so build a new aggregator instead.

Return type:

None

get_results()[source]

Close the merge and return the combined ranking.

Closes the aggregator: a later add_results() raises. Calling this again returns the same ranking.

Returns:

QueryNamespacesResults with matches (the merged top-k, best first), usage (read units summed over every namespace) and ns_usage (read units per namespace).

Return type:

QueryNamespacesResults

Document Models

The document interface — index.documents on either client — works in whole records rather than raw vectors. You write DocumentRecord and read back Document.

class pinecone.models.documents.document.Document(data)[source]

Bases: object

One document a search or fetch returned: its ID, its score, and your own fields.

Read the identifier as ``doc.id``. doc._id returns the same string and is kept so that code written against the wire shape keeps working, but doc.id is the canonical spelling in this SDK and the one every example uses. The same holds for doc.score over doc._score. The underscore forms belong to the JSON, not to your Python.

Your own fields are reachable as attributes (doc.title) and through get(); which of them are present depends on the include_fields the operation asked for. An absent field raises AttributeError on attribute access, so use get() when a field is optional.

The id, _id, score and _score properties always win over a document field of the same name. If your data genuinely has a field called _score, reach it with doc.get("_score") or doc.to_dict()["_score"].

Variables:
  • id (str) – The document’s identifier — the value the document was upserted under.

  • _id (str) – Alias for id, matching the JSON key. Prefer id.

  • score (float | None) – How well the document matched, or None when the response carried no score. A fetch returns documents without scores, so None there is normal rather than a sign anything went wrong.

  • _score (float | None) – Alias for score, matching the JSON key. Prefer score.

Parameters:

data (dict[str, Any])

Examples

>>> from pinecone import Document
>>> doc = Document({"_id": "article-42", "_score": 0.891, "title": "Rome"})
>>> doc.id, doc.score
('article-42', 0.891)
>>> doc.title
'Rome'
>>> doc.get("subtitle", "n/a")
'n/a'

A fetched document has no score:

>>> Document({"_id": "article-42", "title": "Rome"}).score is None
True
__init__(data)[source]
Parameters:

data (dict[str, Any])

Return type:

None

property id: str
property score: float | None
get(key, default=None)[source]

Read a field without risking AttributeError if it is absent.

Behaves like dict.get() over the document. Reserved keys are readable here under their JSON names — get("_id") and get("_score") — which is also the only way to reach a field of your own that happens to be named _score.

Parameters:
  • key (str) – Field name to read, e.g. "title".

  • default (Any) – What to return when the field is absent. Defaults to None.

Returns:

The field’s value, or default.

Return type:

Any

Examples

>>> from pinecone import Document
>>> doc = Document({"_id": "article-42", "title": "Rome"})
>>> doc.get("title"), doc.get("subtitle", "n/a")
('Rome', 'n/a')
to_dict()[source]

Return the document as a plain dict, back in its JSON shape.

A shallow copy, so mutating it does not touch the document. The reserved keys come back under their JSON names — _id and _score — alongside your own fields, which makes this the form to re-serialize or to feed to a DocumentRecord.

Returns:

A dict of every key the document carries.

Return type:

dict[str, Any]

to_json()[source]

Return the document as a compact JSON string, already decoded to str.

Return type:

str

class pinecone.models.documents.document.DocumentRecord(data=None, /, **fields)[source]

Bases: object

A document you are about to upsert, checked before it can reach the wire.

A record is one required reserved key, _id, plus as many fields of your own as you like. _id sits in the same dict as those fields but it is not one of them: it names the document rather than storing anything, and the leading underscore is what marks it as reserved. Passing keyword arguments instead of a dict makes the split plain, since _id= reads as the argument it is.

Your field values are the same shapes metadata takes — a string, a number, a boolean, or a list of strings. A field the index schema declares as dense_vector takes a list of floats, and one declared sparse_vector takes sparse values. Field values are checked against the index schema server-side, so a type mismatch surfaces on upsert rather than here.

Only the _id is validated on construction — a string of 1 to 512 ASCII characters — so a bad ID is reported at the line that wrote it.

Parameters:
  • data (dict[str, Any] | None) – The record as a dict, positional-only. Must carry _id. Merged with, and overridden by, any keyword fields.

  • **fields (Any) – Fields given as keyword arguments, including _id.

Raises:

ValueError – If _id is missing, is not a string, is empty, is over 512 characters, or contains a non-ASCII character or NUL.

Examples

Building from keyword arguments keeps the reserved _id visually distinct from the fields you are storing:

>>> from pinecone import DocumentRecord
>>> DocumentRecord(_id="article-42", title="Rome", lang="en").to_dict()
{'_id': 'article-42', 'title': 'Rome', 'lang': 'en'}

A dict works too, which is the form to use when your documents already arrive as JSON. Here _id is the reserved key naming the document and title is a field being stored, even though they sit side by side:

>>> DocumentRecord({"_id": "article-42", "title": "Rome"})
DocumentRecord(_id='article-42', fields=1)

See also

UpdateDocumentRecord — for changing fields on a document that already exists, rather than replacing it wholesale.

__init__(data=None, /, **fields)[source]
Parameters:
Return type:

None

property id: str

The identifier this record will be stored under. The spelling to prefer.

get(key, default=None)[source]

Read a field, or the reserved _id, without raising when it is absent.

Parameters:
  • key (str) – Field name to read, e.g. "title".

  • default (Any) – What to return when the field is absent. Defaults to None.

Returns:

The field’s value, or default.

Return type:

Any

to_dict()[source]

Return the record as a plain dict in JSON shape, with _id among the fields.

A shallow copy, so mutating it does not touch the record.

Return type:

dict[str, Any]

to_json()[source]

Return the record as a compact JSON string, already decoded to str.

Return type:

str

class pinecone.models.documents.document.UpdateDocumentRecord(data=None, /, **fields)[source]

Bases: object

A patch to one existing document: the fields to change, and the fields to drop.

This is a partial update, so fields you do not mention are left exactly as they are — that is the difference from DocumentRecord, which replaces the document.

Two reserved keys shape the patch, and neither one stores a value: _id says which document to patch, and _remove_fields lists field names to delete from it. Every other key is a field being set to a new value. So in a patch dict the underscore keys are instructions and the plain keys are data, even though they appear in the same dict at the same level. Keyword arguments make that split easier to read.

A field cannot be both set and removed in one patch; asking for both is rejected here rather than resolved silently in one direction.

Parameters:
  • data (dict[str, Any] | None) – The patch as a dict, positional-only. Must carry _id. Merged with, and overridden by, any keyword fields.

  • **fields (Any) – Fields to set, given as keyword arguments; _id and _remove_fields may be passed this way too.

Raises:

ValueError – If _id is missing or invalid, if _remove_fields is not a list of strings, or if a field appears both as a new value and in _remove_fields — the message names the overlapping fields.

Examples

Set two fields and leave the rest of the document alone:

>>> from pinecone import UpdateDocumentRecord
>>> UpdateDocumentRecord(_id="article-42", title="Rome", lang="en").remove_fields is None
True

Set one field and delete another in the same patch. _id and _remove_fields are the two reserved keys here; title is the only field being written:

>>> UpdateDocumentRecord(
...     {"_id": "article-42", "title": "Rome", "_remove_fields": ["draft_notes"]}
... )
UpdateDocumentRecord(_id='article-42', set=1, remove=1)

See also

DocumentRecord — for writing a whole document, where unmentioned fields do not survive.

__init__(data=None, /, **fields)[source]
Parameters:
Return type:

None

property id: str

The identifier of the document this patch applies to. The spelling to prefer.

property remove_fields: list[str] | None

Field names this patch deletes, or None when it only sets values.

get(key, default=None)[source]

Read one entry of the patch, reserved keys included, without raising.

Parameters:
  • key (str) – Name to read — a field being set, or "_id" or "_remove_fields".

  • default (Any) – What to return when it is absent. Defaults to None.

Returns:

The value, or default.

Return type:

Any

to_dict()[source]

Return the patch as a plain dict in JSON shape, reserved keys included.

A shallow copy, so mutating it does not touch the record.

Return type:

dict[str, Any]

to_json()[source]

Return the patch as a compact JSON string, already decoded to str.

Return type:

str

class pinecone.models.documents.responses.ListedDocumentRecord(*, id)[source]

Bases: Struct

One document ID from a list, and nothing else.

This is what iterating idx.documents.list(...) yields. A list walks the IDs in a namespace without reading the documents, so none of your fields are here — fetch the IDs you want to read. The identifier is entry.id; entry._id is the same value under the JSON key name.

Variables:

id (str) – The document’s identifier. JSON key _id.

Parameters:

id (str)

Examples

for entry in idx.documents.list(namespace="articles-en", prefix="article-"):
    print(entry.id)
id: str

Document Scoring

score_by picks how a search ranks candidates. Pass one of these query types.

pinecone.models.documents.score_by.DocumentScoringMethod = pinecone.models.documents.score_by.TextQuery | pinecone.models.documents.score_by.QueryStringQuery | pinecone.models.documents.score_by.DenseVectorQuery | pinecone.models.documents.score_by.SparseVectorQuery

Represent a PEP 604 union type

E.g. for int | str

class pinecone.models.documents.score_by.TextQuery(*, query, fields=None, field=None)[source]

Bases: Struct

Score documents by BM25 keyword relevance over named text fields.

The clause to reach for when the words themselves matter — exact terms, names, codes — rather than meaning. Scoring is per field, so name every field you want searched.

Variables:
  • query (str) – The words to search for, e.g. "sparse index scoring".

  • fields (list[str] | None) – The text fields to search across, e.g. ["title", "chunk"]. At least one is required.

  • field (str | None) – Deprecated single-field form of fields. A value here is moved into fields with a DeprecationWarning and this attribute reads back as None, so read fields whichever way you set it.

Raises:

ValueError – If fields ends up empty, or if both fields and field are given.

Parameters:

Examples

>>> from pinecone.models.documents.score_by import TextQuery
>>> TextQuery(query="sparse index scoring", fields=["title", "chunk"]).fields
['title', 'chunk']

See also

QueryStringQuery — when you need boolean operators in the query itself.

query: str
fields: list[str] | None
field: str | None
class pinecone.models.documents.score_by.QueryStringQuery(*, query, field=None, fields=None)[source]

Bases: Struct

Score documents by a Lucene query string, with AND, OR and NOT.

Choose this over TextQuery when the query itself needs structure — combining terms, excluding one, or scoping a clause to one field. Fields are named inside the query string as field_name:(clause); leave the qualifiers off and every text-searchable field is searched.

Variables:
  • query (str) – The Lucene expression, e.g. 'title:(sparse OR hybrid) NOT draft'.

  • field (str | None) – Not accepted here — use a qualifier in query instead.

  • fields (list[str] | None) – Not accepted here — use a qualifier in query instead.

Raises:

ValueError – If field or fields is given. Passing either is rejected rather than ignored, because the field would silently not be applied.

Parameters:

Examples

>>> from pinecone.models.documents.score_by import QueryStringQuery
>>> QueryStringQuery(query="title:(sparse OR hybrid) NOT draft").query
'title:(sparse OR hybrid) NOT draft'
query: str
field: str | None
fields: list[str] | None
class pinecone.models.documents.score_by.DenseVectorQuery(*, field, values)[source]

Bases: Struct

Score documents by dense vector similarity to a query embedding.

The clause for finding documents by meaning. It scores against one field, so the field named has to be declared dense_vector in the index schema, and values has to be as long as that field’s dimension. A dense clause cannot be combined with any other scoring method in the same search.

Variables:
  • field (str) – The dense vector field to score against, e.g. "embedding".

  • values (list[float]) – The query embedding, one float per dimension of that field.

Raises:

ValueError – If field is empty, or values is empty.

Parameters:

Examples

The three floats here stand in for a full-length embedding.

>>> from pinecone.models.documents.score_by import DenseVectorQuery
>>> DenseVectorQuery(field="embedding", values=[0.12, 0.34, 0.56]).field
'embedding'

See also

SparseVectorQuery — the same idea against a sparse field.

field: str
values: list[float]
class pinecone.models.documents.score_by.SparseVectorQuery(*, field, sparse_values)[source]

Bases: Struct

Score documents by sparse vector similarity to a query sparse vector.

The clause for finding documents by term overlap when you already hold a sparse encoding of the query. The field named has to be declared sparse_vector in the index schema, and, like a dense clause, this one cannot be combined with any other scoring method in the same search.

Variables:
Raises:

ValueError – If field is empty.

Parameters:

Examples

>>> from pinecone import SparseValues
>>> from pinecone.models.documents.score_by import SparseVectorQuery
>>> SparseVectorQuery(
...     field="keywords",
...     sparse_values=SparseValues(indices=[10, 42], values=[0.4, 0.9]),
... ).field
'keywords'

See also

TextQuery — when you have the words rather than a sparse encoding of them.

field: str
sparse_values: SparseValues

Document Responses

class pinecone.models.documents.responses.UpsertDocumentsResponse(*, upserted_count, response_info=None)[source]

Bases: Struct

What a document upsert wrote.

Variables:
Parameters:
upserted_count: int
response_info: ResponseInfo | None
class pinecone.models.documents.responses.SearchDocumentsResponse(matches, namespace, usage=None, response_info=None)[source]

Bases: object

The ranked documents a search found.

matches is already ordered, so matches[0] is the best hit. Each element is a Document: read doc.id and doc.score, then your own fields by name. Which fields are present depends on the search’s include_fields — by default only the ID and the score come back, so ask for the fields you intend to read. A search that matched nothing returns an empty matches rather than raising.

Variables:
Parameters:

Examples

response = idx.documents.search(
    namespace="articles-en",
    score_by=[{"type": "text", "query": "vector search", "fields": ["title"]}],
    top_k=5,
    include_fields=["title"],
)
for doc in response.matches:
    print(doc.id, doc.score, doc.title)
matches: list[Document]
namespace: str
usage: DocumentSearchUsage | None
response_info: ResponseInfo | None
__init__(matches, namespace, usage=None, response_info=None)[source]
Parameters:
Return type:

None

classmethod from_dict(data, *, response_info=None)[source]

Build a response from an already-decoded search body.

Fields the SDK does not know about are kept verbatim on each wrapped Document.

Parameters:
  • data (dict[str, Any]) – The decoded response body.

  • response_info (ResponseInfo | None) – HTTP response metadata to attach, or None. Keyword-only.

Returns:

SearchDocumentsResponse with one Document per match.

Return type:

SearchDocumentsResponse

to_dict()[source]

Return the response as a plain dict in its JSON shape.

Reserved keys come back under their JSON names, so each document carries _id and, for a search, _score.

Return type:

dict[str, Any]

class pinecone.models.documents.responses.FetchDocumentsResponse(documents, namespace, usage=None, pagination=None, response_info=None)[source]

Bases: object

The documents a fetch retrieved, keyed by ID.

documents is a dict, so look a document up by the ID you asked for. An ID that does not exist is simply absent — fetching a missing ID is not an error — so test membership rather than indexing blind. Unlike a search, a fetch returns every field by default.

Variables:
Parameters:

Examples

wanted = ["article-101", "article-102"]
response = idx.documents.fetch(ids=wanted, namespace="articles-en")
for doc_id, doc in response.documents.items():
    print(doc_id, doc.title)
print("not stored:", [d for d in wanted if d not in response.documents])
documents: dict[str, Document]
namespace: str
usage: DocumentFetchUsage | None
pagination: Pagination | None
response_info: ResponseInfo | None
__init__(documents, namespace, usage=None, pagination=None, response_info=None)[source]
Parameters:
Return type:

None

classmethod from_dict(data, *, response_info=None)[source]

Build a response from an already-decoded fetch body.

Fields the SDK does not know about are kept verbatim on each wrapped Document.

Parameters:
  • data (dict[str, Any]) – The decoded response body.

  • response_info (ResponseInfo | None) – HTTP response metadata to attach, or None. Keyword-only.

Returns:

FetchDocumentsResponse keyed by document ID.

Return type:

FetchDocumentsResponse

to_dict()[source]

Return the response as a plain dict in its JSON shape.

Reserved keys come back under their JSON names, so each document carries _id and, for a search, _score.

Return type:

dict[str, Any]

class pinecone.models.documents.responses.ListDocumentsResponse(*, documents, namespace, usage, pagination=None, response_info=None)[source]

Bases: Struct

One decoded page of a document list, as it comes off the wire.

idx.documents.list does not hand this to you — it returns a Paginator that consumes these pages and yields the ListedDocumentRecord entries, following pagination for you. Read this model when you are driving the paging yourself.

Variables:
Parameters:

See also

Pagination — which pagination shape applies where, and the paginator that saves you writing the loop.

documents: list[ListedDocumentRecord]
namespace: str
usage: DocumentListUsage
pagination: Pagination | None
response_info: ResponseInfo | None
class pinecone.models.documents.responses.UpdateDocumentsResponse(*, matched_records=None, response_info=None)[source]

Bases: Struct

Confirmation that a document update was accepted, and what it matched.

Variables:
  • matched_records (int | None) – The number of documents that matched filter when the update was accepted. Only returned for a filtered update — None for per-ID updates and when the count could not be read in time. The patch is applied asynchronously, so this is a point-in-time count rather than a guarantee of the number of documents ultimately patched.

  • response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or None when not present.

Parameters:
matched_records: int | None
response_info: ResponseInfo | None
class pinecone.models.documents.responses.DeleteDocumentsResponse(*, matched_records=None, response_info=None)[source]

Bases: Struct

Confirmation that a document delete was accepted, and what it matched.

Variables:
  • matched_records (int | None) – The number of documents that matched filter when the delete was accepted. Only returned for a filtered delete — None for by-id and delete-all paths, and when the count could not be read in time. 0 means the filter matched no documents. The delete is applied asynchronously, so this is a point-in-time count rather than a guarantee of the number of documents ultimately deleted.

  • response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or None when not present.

Parameters:
matched_records: int | None
response_info: ResponseInfo | None
class pinecone.models.documents.responses.DocumentSearchUsage(*, read_units)[source]

Bases: Struct

What one document search cost.

Variables:

read_units (int) – Read units this call consumed.

Parameters:

read_units (int)

read_units: int
class pinecone.models.documents.responses.DocumentFetchUsage(*, read_units)[source]

Bases: Struct

What one document fetch cost.

Variables:

read_units (int) – Read units this call consumed.

Parameters:

read_units (int)

read_units: int
class pinecone.models.documents.responses.DocumentListUsage(*, read_units)[source]

Bases: Struct

What one document list cost.

Variables:

read_units (int) – Read units this call consumed.

Parameters:

read_units (int)

read_units: int

Document Requests

Document methods are keyword-only; you never build one of these yourself. They document the request body each method sends, which is what you are reading when a validation error names a field.

class pinecone.models.documents.requests.UpsertDocumentsRequest(*, documents)[source]

Bases: Struct

The body of an upsert on index.documents.

Variables:

documents (list[dict[str, Any] | pinecone.models.documents.document.DocumentRecord]) – The documents to write, 1 to 1000 of them. Each may be a DocumentRecord or a plain dict carrying the reserved _id key alongside your own fields; either way the _id is validated here, so a bad one is reported before anything is sent. An upsert replaces the whole document, so a field you leave out of a document you are rewriting does not survive.

Raises:

ValueError – If documents is empty, holds more than 1000 documents, or contains a document whose _id is missing or invalid.

Parameters:

documents (list[dict[str, Any] | DocumentRecord])

documents: list[dict[str, Any] | DocumentRecord]
class pinecone.models.documents.requests.SearchDocumentsRequest(*, score_by, top_k, include_fields=None, filter=None)[source]

Bases: Struct

The body of a search on index.documents.

Variables:
Raises:

ValueError – If score_by is empty or holds over 100 clauses, if a vector clause is combined with another clause, or if top_k is outside 1 to 10000.

Parameters:
score_by: list[TextQuery | QueryStringQuery | DenseVectorQuery | SparseVectorQuery | dict[str, Any]]
top_k: int
include_fields: list[str] | None
filter: dict[str, Any] | None
class pinecone.models.documents.requests.FetchDocumentsRequest(*, ids=None, filter=None, include_fields=None, pagination_token=None)[source]

Bases: Struct

The body of a fetch on index.documents.

Select the documents one way or the other: exactly one of ids and filter must be given. Only the filter form pages, since only it can match an unbounded number of documents.

Variables:
  • ids (list[str] | None) – The document IDs to fetch, 1 to 1000. Mutually exclusive with filter.

  • filter (dict[str, Any] | None) – A non-empty metadata filter selecting the documents to fetch. Mutually exclusive with ids.

  • include_fields (list[str] | None) – Which of your fields to return. Omitting it, passing [], and passing ["*"] all return every field — the opposite of the default on a search, which returns none of them.

  • pagination_token (str | None) – The token from a previous fetch response, to get the next page. Valid only with filter; the server chooses the page size.

Raises:

ValueError – If both or neither of ids and filter are given, if filter is an empty object, if ids holds over 1000 IDs, or if pagination_token is given without filter.

Parameters:
ids: list[str] | None
filter: dict[str, Any] | None
include_fields: list[str] | None
pagination_token: str | None
class pinecone.models.documents.requests.ListDocumentsRequest(*, prefix=None, limit=None, pagination_token=None)[source]

Bases: Struct

The body of a list on index.documents.

A list walks IDs, not documents, so none of your fields come back — use it to enumerate a namespace, then fetch the IDs you want.

Variables:
  • prefix (str | None) – Return only IDs starting with this string, e.g. "article-". ASCII, at most 512 characters. None lists every ID.

  • limit (int | None) – How many IDs per page, 1 to 100, or None to let the server choose.

  • pagination_token (str | None) – The token from a previous list response, to get the next page.

Raises:

ValueError – If prefix is over 512 characters or contains a non-ASCII character or NUL, or if limit is outside 1 to 100.

Parameters:
  • prefix (str | None)

  • limit (int | None)

  • pagination_token (str | None)

prefix: str | None
limit: int | None
pagination_token: str | None
class pinecone.models.documents.requests.UpdateDocumentsRequest(*, documents=None, filter=None, set_fields=None, remove_fields=None)[source]

Bases: Struct

The body of an update on index.documents, in either of its two forms.

Patch named documents individually with documents, or patch every document a filter matches with filter plus set_fields and/or remove_fields. The two forms are mutually exclusive. Either way this is a partial update: fields you do not name survive.

Variables:
  • documents (list[dict[str, Any] | pinecone.models.documents.document.UpdateDocumentRecord] | None) – Per-document patches, 1 to 1000. Each may be an UpdateDocumentRecord or a plain dict; in the dict form _id and _remove_fields are reserved keys and every other key is a field being set. Mutually exclusive with the by-filter fields.

  • filter (dict[str, Any] | None) – A non-empty metadata filter selecting the documents to patch. A text-match operator here is rejected rather than ignored, since evaluated in a filter it would widen the patch. Mutually exclusive with documents.

  • set_fields (dict[str, Any] | None) – Fields to set, and their new values, on every document filter matches.

  • remove_fields (list[str] | None) – Field names to delete from every document filter matches.

Raises:

ValueError – If documents is combined with any by-filter field, if neither selector is given, if set_fields or remove_fields is given without a filter, if a filter is given with nothing to change, if filter is an empty object, or if documents is empty or holds over 1000 patches.

Parameters:
documents: list[dict[str, Any] | UpdateDocumentRecord] | None
filter: dict[str, Any] | None
set_fields: dict[str, Any] | None
remove_fields: list[str] | None
class pinecone.models.documents.requests.DeleteDocumentsRequest(*, ids=None, filter=None, delete_all=None)[source]

Bases: Struct

The body of a delete on index.documents.

Exactly one of the three selectors must be given, so a delete always states its scope explicitly and there is no way to write one that means “everything” by omission.

Variables:
  • ids (list[str] | None) – The document IDs to delete, 1 to 1000. Mutually exclusive with the others.

  • filter (dict[str, Any] | None) – A non-empty metadata filter selecting the documents to delete. A text-match operator here is rejected rather than ignored, since evaluated in a filter it would widen the delete. Mutually exclusive with the others.

  • delete_all (bool | None) – True deletes every document in the namespace. Mutually exclusive with the others.

Raises:

ValueError – If more than one selector is given, if none is, if filter is an empty object, or if ids holds over 1000 IDs.

Parameters:
ids: list[str] | None
filter: dict[str, Any] | None
delete_all: bool | None

Inference Models

class pinecone.models.inference.embed.DenseEmbedding(*, values, vector_type='dense')[source]

Bases: DictLikeStruct, Struct

One embedding from a dense model, as a list of floats.

values is the vector, ready to pass to upsert() or as a query vector. Its length is the model’s output dimension, which get_model() reports as default_dimension.

Variables:
  • values (list[float]) – The embedding, one float per dimension.

  • vector_type (str) – Always "dense".

Parameters:
values: list[float]
vector_type: str
class pinecone.models.inference.embed.SparseEmbedding(*, sparse_values, sparse_indices, sparse_tokens=None, vector_type='sparse')[source]

Bases: StructDictMixin, Struct

One embedding from a sparse model, stored as index/value pairs.

There is no values field here — the vector lives in sparse_indices and sparse_values, paired position by position. Reading .values on one of these hands back a dict-view method rather than a vector and raises nothing to warn you, so branch on the enclosing EmbeddingsList’s vector_type when the model is not fixed in advance.

Variables:
  • sparse_values (list[float]) – The non-zero values of the sparse embedding.

  • sparse_indices (list[int]) – The index each of those values sits at.

  • sparse_tokens (list[str] | None) – The token each index came from, when the model reports them; None otherwise.

  • vector_type (str) – Always "sparse".

Parameters:
sparse_values: list[float]
sparse_indices: list[int]
sparse_tokens: list[str] | None
vector_type: str
pinecone.models.inference.embed.Embedding = pinecone.models.inference.embed.DenseEmbedding | pinecone.models.inference.embed.SparseEmbedding

Represent a PEP 604 union type

E.g. for int | str

class pinecone.models.inference.embed.EmbeddingsList(*, model, vector_type, data, usage)[source]

Bases: Struct

What embed() returns.

One embedding per input, in the order the inputs were given. Iterating the list is the usual way in; integer indexing and len() reach the same items, and bracket access with a field name (embeddings["model"]) reads the fields below. Returned by the SDK rather than constructed by callers.

Variables:
Parameters:

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> embeddings = pc.inference.embed(
...     model="multilingual-e5-large",
...     inputs=[
...         "Vector databases index embeddings for similarity search.",
...         "Reranking reorders candidate results by relevance.",
...     ],
...     parameters={"input_type": "passage"},
... )
>>> len(embeddings)
2
>>> [embedding.vector_type for embedding in embeddings]
['dense', 'dense']
>>> embeddings["model"]
'multilingual-e5-large'
model: str
vector_type: str
data: list[DenseEmbedding] | list[SparseEmbedding]
usage: EmbedUsage
to_dict()[source]

Return a plain dict representation of this object.

Return type:

dict[str, Any]

class pinecone.models.inference.embed.EmbedUsage(*, total_tokens)[source]

Bases: StructDictMixin, Struct

Token usage information for an embedding request.

Variables:

total_tokens (int) – Total number of tokens processed.

Parameters:

total_tokens (int)

total_tokens: int
class pinecone.models.inference.rerank.RerankResult(*, model, data, usage)[source]

Bases: Struct

What rerank() returns.

Bracket access with a field name (result["model"]) reads the fields below. Returned by the SDK rather than constructed by callers.

Variables:
Parameters:

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> result = pc.inference.rerank(
...     model="bge-reranker-v2-m3",
...     query="Tell me about tech companies",
...     documents=["Apple is a fruit.", "Acme Inc. revolutionized tech."],
...     top_n=1,
... )
>>> result.data[0].index
1
>>> result.data[0].document["text"]
'Acme Inc. revolutionized tech.'
>>> result["model"]
'bge-reranker-v2-m3'
model: str
data: list[RankedDocument]
usage: RerankUsage
to_dict()[source]

Return a plain dict representation of this object.

Return type:

dict[str, Any]

class pinecone.models.inference.rerank.RankedDocument(*, index, score, document=None)[source]

Bases: StructDictMixin, Struct

One document and the score the reranker gave it.

index is where the document sat in the request, not where it sits in the reordered result — it is what maps a result back onto the list you passed in.

Variables:
  • index (int) – The position this document held in the documents argument.

  • score (float) – The relevance the reranker assigned, higher being closer to the query.

  • document (dict[str, Any] | None) – The document as sent, unless return_documents=False was passed, in which case None.

Parameters:
index: int
score: float
document: dict[str, Any] | None
class pinecone.models.inference.rerank.RerankUsage(*, rerank_units)[source]

Bases: StructDictMixin, Struct

Usage information for a rerank request.

Variables:

rerank_units (int) – Number of rerank units consumed.

Parameters:

rerank_units (int)

rerank_units: int
class pinecone.models.inference.models.ModelInfo(*, model, short_description, type, supported_parameters, vector_type=None, default_dimension=None, supported_dimensions=None, modality=None, max_sequence_length=None, max_batch_size=None, provider_name=None, supported_metrics=None)[source]

Bases: Struct

What one inference model is and what it will accept.

Returned by get_model(), and by list_models() for every model in the listing. The embed-only fields below are None on a reranking model, so read type before relying on them. Bracket access with a field name (info["model"]) reads the fields too.

Variables:
  • model (str) – The model identifier — what to pass as model=. Also readable as name.

  • short_description (str) – A brief description of the model. Also readable as description.

  • type (str) – "embed" or "rerank".

  • supported_parameters (list[pinecone.models.inference.models.ModelInfoSupportedParameter]) – The ModelInfoSupportedParameter entries describing what parameters= will take for this model.

  • vector_type (str | None) – For embedding models, "dense" or "sparse".

  • default_dimension (int | None) – For embedding models, the output dimension used when none is requested.

  • supported_dimensions (list[int] | None) – For embedding models, every output dimension the model can produce.

  • modality (str | None) – The input modality (e.g. "text").

  • max_sequence_length (int | None) – The longest input the model accepts.

  • max_batch_size (int | None) – The most inputs one request may carry.

  • provider_name (str | None) – Who supplies the model.

  • supported_metrics (list[str] | None) – The similarity metrics an index built on this model’s vectors can use.

Parameters:

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> info = pc.inference.get_model(model="multilingual-e5-large")
>>> info.type, info.vector_type, info.default_dimension
('embed', 'dense', 1024)
>>> info.name == info.model
True
model: str
short_description: str
type: str
supported_parameters: list[ModelInfoSupportedParameter]
vector_type: str | None
default_dimension: int | None
supported_dimensions: list[int] | None
modality: str | None
max_sequence_length: int | None
max_batch_size: int | None
provider_name: str | None
supported_metrics: list[str] | None
property name: str

Alias for model — the model identifier.

property description: str

Alias for short_description — a brief description of the model.

to_dict()[source]

Return a plain dict representation of this object.

Return type:

dict[str, Any]

class pinecone.models.inference.models.ModelInfoSupportedParameter(*, parameter, type, value_type, required, allowed_values=None, min=None, max=None, default=None)[source]

Bases: Struct

One key a model accepts in a parameters argument, and its bounds.

Read these off ModelInfo’s supported_parameters to learn what parameters= will take for a given model, rather than guessing and catching the rejection.

Variables:
  • parameter (str) – The key to use in parameters, e.g. "input_type".

  • type (str) – How the value is constrained (e.g. "one_of" for a fixed set).

  • value_type (str) – The value type (e.g. "string").

  • required (bool) – Whether the parameter must be sent.

  • allowed_values (list[str | int] | None) – The values accepted, when the set is fixed.

  • min (int | float | None) – Minimum value, for numeric parameters.

  • max (int | float | None) – Maximum value, for numeric parameters.

  • default (str | int | float | bool | None) – What the model uses when the key is omitted.

Parameters:
parameter: str
type: str
value_type: str
required: bool
allowed_values: list[str | int] | None
min: int | float | None
max: int | float | None
default: str | int | float | bool | None
class pinecone.models.inference.model_list.ModelInfoList(models)[source]

Bases: object

What list_models() returns.

Iterate it to reach each ModelInfo; integer indexing, len() and the string key ["models"] work too. Returned by the SDK rather than constructed by callers.

Variables:

models – The underlying list of ModelInfo instances.

Parameters:

models (list[ModelInfo])

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> models = pc.inference.list_models()
>>> for info in models:
...     print(info.model, info.type)
multilingual-e5-large embed
pinecone-sparse-english-v0 embed
bge-reranker-v2-m3 rerank
__init__(models)[source]

Initialize a ModelInfoList.

Parameters:

models (list[ModelInfo]) – List of ModelInfo instances.

Return type:

None

property models: list[ModelInfo]

Return the underlying list of models.

names()[source]

Return just the model identifiers, in listing order.

Returns:

The model field of each ModelInfo — the names accepted by model= on embed() and rerank().

Return type:

list[str]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> models = pc.inference.list_models()
>>> models.names()
['multilingual-e5-large', 'pinecone-sparse-english-v0', 'bge-reranker-v2-m3']
to_dict()[source]

Return a plain dict representation of this list.

Return type:

dict[str, Any]

class pinecone.inference.models.index_embed.IndexEmbed(model, field_map, metric=None, read_parameters=<factory>, write_parameters=<factory>)[source]

Bases: object

Which model embeds an integrated index, and which field it embeds.

Accepted as the embed argument of create_index_for_model(), alongside a plain dict and EmbedConfig. Kept here, and importable from pinecone, for code written against earlier releases.

Parameters:
model: str
field_map: dict[str, Any]
metric: str | None = None
read_parameters: dict[str, Any]
write_parameters: dict[str, Any]
as_dict()[source]

Return the instance’s field values as a plain dictionary.

Return type:

dict[str, Any]

__init__(model, field_map, metric=None, read_parameters=<factory>, write_parameters=<factory>)
Parameters:
Return type:

None

Import Models

class pinecone.models.imports.model.ImportModel(*, id, uri, status, created_at, finished_at=None, percent_complete=None, records_imported=None, error=None)[source]

Bases: StructDictMixin, Struct

The current state of one bulk import, as describe_import reports it.

A bulk import runs server-side after you start it, so this is the model you poll. Three fields answer the questions worth asking: status says whether it is still running, percent_complete says how far along, and records_imported says how much has actually landed. Poll until status is a terminal value — Completed, Failed, or Cancelled — and read error when it is Failed.

Variables:
  • id (str) – Identifier of the import, the value to pass back to describe_import and cancel_import.

  • uri (str) – Where the data is being read from.

  • status (str) – Pending, InProgress, Failed, Completed or Cancelled. The first two mean keep polling; the rest are terminal.

  • created_at (str) – When the import was created, as a timestamp string.

  • finished_at (str | None) – When the import stopped running, or None while it is still running.

  • percent_complete (float | None) – How far along the import is, or None before the server has a figure. Progress alone is not completion — status is the authority.

  • records_imported (int | None) – Records written so far, or None before the server has a figure. A Failed import can leave this above zero, so a failure does not imply nothing was written.

  • error (str | None) – Why the import failed, or None. Populated only for Failed.

Parameters:
  • id (str)

  • uri (str)

  • status (str)

  • created_at (str)

  • finished_at (str | None)

  • percent_complete (float | None)

  • records_imported (int | None)

  • error (str | None)

Examples

operation = idx.describe_import(id=import_id)
print(operation.status, operation.percent_complete, operation.records_imported)
if operation.status == "Failed":
    print(operation.error)

See also

How Bulk Ingest Behaves — preparing the source data and choosing an error mode.

id: str
uri: str
status: str
created_at: str
finished_at: str | None
percent_complete: float | None
records_imported: int | None
error: str | None
class pinecone.models.imports.list.ImportList(imports, *, pagination=None)[source]

Bases: object

One page of ImportModel objects, iterable and sized like a list.

What list_imports_paginated returns. Iterate it, index into it, or take len(); pagination carries the token for the next page, and is None when this is the last one.

Variables:

pagination – Token for the next page, or None when there are no more.

Parameters:

Examples

page = idx.list_imports_paginated()
for operation in page:
    print(operation.id, operation.status, operation.percent_complete)

See also

How Bulk Ingest Behaves — starting and monitoring imports.

__init__(imports, *, pagination=None)[source]

Wrap a page of imports.

Parameters:
  • imports (list[ImportModel]) – The imports on this page.

  • pagination (Pagination | None) – Token for the next page, or None when this is the last page. Keyword-only.

Return type:

None

to_dict()[source]

Return the page as a plain, JSON-serializable dict.

Returns:

A dict whose "data" key holds one dict per import, each from ImportModel.to_dict(). A "pagination" key is present only when there is a next page.

Return type:

dict[str, Any]

Examples

>>> idx = pc.index(name="article-search")
>>> idx.list_imports_paginated().to_dict()
{'data': []}
class pinecone.models.imports.model.StartImportResponse(*, id)[source]

Bases: StructDictMixin, Struct

The handle start_import returns: an ID, and nothing else yet.

Starting an import is asynchronous, so this comes back before any data has been read. Keep the id — it is the only way to check on the import afterwards, or to cancel it.

Variables:

id (str) – Identifier of the import just created. Pass it to describe_import to poll ImportModel, or to cancel_import to stop it.

Parameters:

id (str)

See also

How Bulk Ingest Behaves — the whole start-then-poll flow.

id: str
class pinecone.models.imports.error_mode.ImportErrorMode(value)[source]

Bases: str, Enum

What a bulk import does when one record fails: skip it, or stop.

Pass this as error_mode on start_import. The choice is about how you would rather find out about bad data: ABORT surfaces the first bad record immediately and imports nothing, which suits data you expect to be clean; CONTINUE loads everything else and leaves you to reconcile what is missing, which suits a large source you would rather not restart.

Variables:
  • CONTINUE – Skip the failing record and keep importing the rest.

  • ABORT – Stop the whole import at the first failing record. This is what you get by omitting error_mode.

Examples

from pinecone import ImportErrorMode

operation = idx.start_import(
    uri="s3://my-bucket/articles/", error_mode=ImportErrorMode.CONTINUE
)

See also

How Bulk Ingest Behaves — the source-data layout an import expects.

CONTINUE = 'continue'
ABORT = 'abort'

Collection Models

class pinecone.models.collections.model.CollectionModel(*, name, status, environment, size=None, dimension=None, vector_count=None)[source]

Bases: StructDictMixin, Struct

One collection, as returned by Collections.create(), Collections.describe(), and iteration over CollectionList.

Only name, status, and environment are populated while the snapshot is still being built; read status before trusting the rest.

Variables:
  • name (str) – The name of the collection.

  • status (str) – Current status of the collection (e.g. "Ready", "Initializing", "Terminating").

  • environment (str) – Deployment environment where the collection is hosted.

  • size (int | None) – Space the snapshot occupies, in bytes — not a vector dimension. None until the collection is built.

  • dimension (int | None) – Dimensionality of vectors in the collection, or None until the collection is built.

  • vector_count (int | None) – Number of vectors in the collection, or None until the collection is built.

Parameters:
  • name (str)

  • status (str)

  • environment (str)

  • size (int | None)

  • dimension (int | None)

  • vector_count (int | None)

Examples

>>> col = pc.collections.describe("movie-embeddings-snapshot")
>>> col.status, col.dimension, col.vector_count
('Ready', 1024, 99)
name: str
status: str
environment: str
size: int | None
dimension: int | None
vector_count: int | None
class pinecone.models.collections.list.CollectionList(collections)[source]

Bases: object

The collections in a project, as returned by Collections.list().

Iterating yields CollectionModel objects. len() and integer indexing work too, and every collection in the project is present — there is no pagination to follow.

Examples

>>> collections = pc.collections.list()
>>> len(collections)
2
>>> collections[0].name
'movie-embeddings-snapshot'
Parameters:

collections (list[CollectionModel])

__init__(collections)[source]
Parameters:

collections (list[CollectionModel])

Return type:

None

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of collection dicts, each produced by CollectionModel.to_dict().

Return type:

dict[str, Any]

Examples

>>> collections = pc.collections.list()
>>> payload = collections.to_dict()
>>> [c["name"] for c in payload["data"]]
['movie-embeddings-snapshot', 'product-catalog-snapshot']
>>> sorted(payload["data"][0])
['dimension', 'environment', 'name', 'size', 'status', 'vector_count']
names()[source]

Return just the collection names, in the order the API returned them.

Examples

>>> pc.collections.list().names()
['movie-embeddings-snapshot', 'product-catalog-snapshot']
Return type:

list[str]

class pinecone.models.collections.description.CollectionDescription(name, source)[source]

Bases: NamedTuple

Basic metadata describing a collection.

Variables:
  • name (str) – The name of the collection.

  • source (str) – The source index used to create the collection.

Parameters:
name: str

Alias for field number 0

source: str

Alias for field number 1

Backup and Restore Models

class pinecone.models.backups.model.BackupModel(*, backup_id, source_index_name, source_index_id, status, cloud, region, source_index_deleted_at=None, name=None, description=None, schema=None, record_count=None, namespace_count=None, size_bytes=None, tags=None, created_at=None)[source]

Bases: Struct

One stored, point-in-time snapshot of an index.

Returned by create(), describe() and the backup listings; not constructed directly.

Variables:
  • backup_id (str) – Unique identifier for the backup.

  • source_index_name (str) – Name of the index that was backed up.

  • source_index_id (str) – Unique identifier of the source index.

  • status (str) – Current status of the backup — "Initializing", "Ready", or "Failed".

  • cloud (str) – Cloud provider where the backup is stored.

  • region (str) – Region where the backup is stored.

  • source_index_deleted_at (str | None) – Timestamp at which the source index was deleted, or None while the source index is still active. An index-scoped listing only surfaces these rows when it is passed include_deleted=True.

  • name (str | None) – User-provided name for the backup.

  • description (str | None) – User-provided description for the backup.

  • schema (pinecone.models.indexes.schema.IndexSchema | None) – Schema captured from the source index, or None when the server returns no schema (e.g. schedule-produced backups of an index that declared none). Legacy metadata-only schemas decode to LegacyMetadataField entries.

  • record_count (int | None) – Number of records in the backup.

  • namespace_count (int | None) – Number of namespaces in the backup.

  • size_bytes (int | None) – Size of the backup in bytes.

  • tags (dict[str, Any] | None) – User-defined key-value tags, or None when the source index had none (the API returns "tags": null rather than {}).

  • created_at (str | None) – Timestamp when the backup was created.

Parameters:
  • backup_id (str)

  • source_index_name (str)

  • source_index_id (str)

  • status (str)

  • cloud (str)

  • region (str)

  • source_index_deleted_at (str | None)

  • name (str | None)

  • description (str | None)

  • schema (IndexSchema | None)

  • record_count (int | None)

  • namespace_count (int | None)

  • size_bytes (int | None)

  • tags (dict[str, Any] | None)

  • created_at (str | None)

backup_id: str
source_index_name: str
source_index_id: str
status: str
cloud: str
region: str
source_index_deleted_at: str | None
name: str | None
description: str | None
schema: IndexSchema | None
record_count: int | None
namespace_count: int | None
size_bytes: int | None
tags: dict[str, Any] | None
created_at: str | None
property dense_dimension: int | None

Dimension of the backup’s single dense vector field, if there is one.

Returns None when the schema is absent, declares no dense_vector field, or declares more than one — in which case read the dimension off the field you want via schema.fields['<field-name>'].dimension.

to_dict()[source]

Return a dict representation of this backup model.

Returns:

Dictionary with all fields, including optional ones that are None (e.g. name, description, record_count, source_index_deleted_at). schema becomes a plain dict; legacy untyped schema fields are emitted without a type key, matching the wire format.

Return type:

dict[str, Any]

Examples

>>> 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
>>> d["source_index_deleted_at"] is None
True
class pinecone.models.backups.list.BackupList(backups, *, pagination=None)[source]

Bases: object

One page of backups, plus the token for the next page.

Returned by list(); not constructed directly. Iteration, len() and index access all read the page in hand only — list_backups() is the shape that walks every page for you.

Parameters:
__init__(backups, *, pagination=None)[source]

Initialize a BackupList.

Parameters:
  • backups (list[BackupModel]) – List of BackupModel instances representing index backups.

  • pagination (Pagination | None) – Optional Pagination token for fetching additional pages of results.

Return type:

None

property data: list[BackupModel]

Return the list of backups.

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of backup dicts, each produced by BackupModel.to_dict(). When the wrapper has a pagination token, the dict also includes a "pagination" key with the token for fetching the next page.

Return type:

dict[str, Any]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> backups = pc.backups.list(index_name="product-search")
>>> [b["backup_id"] for b in backups.to_dict()["data"]]
['bk-abc123']
>>> "pagination" in backups.to_dict()
False
names()[source]

Return a list of backup names, falling back to backup_id.

If a backup has no name set, its backup_id is used instead.

Returns:

Backup names (or IDs when names are absent).

Return type:

list[str]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> backups = pc.backups.list(index_name="product-search")
>>> backups.names()
['daily-20240115']
class pinecone.models.backups.model.RestoreJobModel(*, restore_job_id, backup_id, target_index_name, target_index_id, status, created_at=None, completed_at=None, percent_complete=None)[source]

Bases: Struct

One attempt at turning a backup back into an index.

Returned by describe() and list(); not constructed directly.

Variables:
  • restore_job_id (str) – Unique identifier for the restore job.

  • backup_id (str) – Identifier of the backup being restored.

  • target_index_name (str) – Name of the index being restored to.

  • target_index_id (str) – Unique identifier of the target index.

  • status (str) – "Pending", "Completed", "Failed", or "Cancelled". There is no in-progress value: a restore that is actively running reports "Pending".

  • created_at (str | None) – Timestamp when the restore job was created, or None if the backend has not yet assigned a creation timestamp.

  • completed_at (str | None) – Timestamp when the restore job completed, or None until then.

  • percent_complete (float | None) – 100 once status is "Completed", and None at every other point — it reports completion rather than progress, so it cannot drive a progress bar.

Parameters:
  • restore_job_id (str)

  • backup_id (str)

  • target_index_name (str)

  • target_index_id (str)

  • status (str)

  • created_at (str | None)

  • completed_at (str | None)

  • percent_complete (float | None)

restore_job_id: str
backup_id: str
target_index_name: str
target_index_id: str
status: str
created_at: str | None
completed_at: str | None
percent_complete: float | None
to_dict()[source]

Return a dict representation of this restore job model.

Returns:

Dictionary with all fields, including optional ones that are None (completed_at and percent_complete). Values are not recursively converted.

Return type:

dict[str, Any]

Examples

>>> from pinecone.models.backups.model import RestoreJobModel
>>> job = RestoreJobModel(
...     restore_job_id="rj-1",
...     backup_id="bkp-1",
...     target_index_name="my-index",
...     target_index_id="idx-abc",
...     status="Pending",
...     created_at="2024-01-01T00:00:00Z",
... )
>>> d = job.to_dict()
>>> d["restore_job_id"]
'rj-1'
>>> d["completed_at"] is None
True
class pinecone.models.backups.list.RestoreJobList(restore_jobs, *, pagination=None)[source]

Bases: object

One page of restore jobs, plus the token for the next page.

Returned by list(); not constructed directly. Iteration, len() and index access all read the page in hand only, and the listing itself is best-effort — see that method’s warning before treating it as an inventory.

Parameters:
__init__(restore_jobs, *, pagination=None)[source]

Initialize a RestoreJobList.

Parameters:
  • restore_jobs (list[RestoreJobModel]) – List of RestoreJobModel instances representing restore operations.

  • pagination (Pagination | None) – Optional Pagination token for fetching additional pages of results.

Return type:

None

property data: list[RestoreJobModel]

Return the list of restore jobs.

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of restore job dicts, each produced by RestoreJobModel.to_dict(). When the wrapper has a pagination token, the dict also includes a "pagination" key with the token for fetching the next page.

Return type:

dict[str, Any]

Examples

from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")
jobs = pc.restore_jobs.list()
print([r["restore_job_id"] for r in jobs.to_dict()["data"]])
class pinecone.models.backups.model.CreateIndexFromBackupRequest(*, name, tags=None, deletion_protection=None, read_capacity=None)[source]

Bases: Struct

Request model for creating an index from a backup.

Optionals you leave unset stay off the wire, so a request built with only name serialises to {"name": ...} and the server applies its own defaults: on-demand read capacity, deletion protection disabled, and the backup’s own tags.

Variables:
  • name (str) – Name for the restored index (required). Subject to the same naming rules as a new index, which the server rather than the client enforces on this path.

  • tags (dict[str, str] | None) – Optional key-value tags for the restored index. When omitted, the server copies the backup’s tags.

  • deletion_protection (str | None) – Optional deletion protection setting ("enabled" or "disabled").

  • read_capacity (dict[str, Any] | None) – Optional read capacity configuration, letting the restore land directly on dedicated read nodes instead of defaulting to on-demand capacity.

Parameters:
name: str
tags: dict[str, str] | None
deletion_protection: str | None
read_capacity: dict[str, Any] | None
class pinecone.models.backups.model.CreateIndexFromBackupResponse(*, restore_job_id, index_id)[source]

Bases: StructDictMixin, Struct

Response model for creating an index from a backup.

Variables:
  • restore_job_id (str) – Identifier of the restore job created.

  • index_id (str) – Identifier of the new index being created.

Parameters:
  • restore_job_id (str)

  • index_id (str)

restore_job_id: str
index_id: str

Backup Schedule Models

class pinecone.models.backups.schedules.BackupScheduleModel(*, schedule_id, name, index_id, project_id, schedule_type, frequency, retention_expire_after_days, enabled, created_at, next_scheduled_run=None)[source]

Bases: Struct

One recurring backup cadence attached to an index.

Returned by every BackupSchedules method that reads or writes a schedule; not constructed directly.

Variables:
  • schedule_id (str) – Unique identifier for the schedule. Used as the path parameter for describe / update / delete / history calls.

  • name (str) – User-defined name for the schedule. Backups it produces are named "{name}-{run timestamp}".

  • index_id (str) – Identifier of the index this schedule backs up. This is the index id, not its name – schedules are created against a name but reported against the id, so a deleted-and-recreated index does not inherit the old schedule.

  • project_id (str) – Project containing the schedule, always the same project as the source index.

  • schedule_type (str) – Schedule category. "time-based" for any schedule created through this SDK, which always sends that value; the server does not constrain the field, so a schedule created by another client can report something else.

  • frequency (str) – Cadence, one of "daily", "weekly", "monthly".

  • retention_expire_after_days (int) – Days each backup produced by this schedule is retained. (The create/update request models spell the same value retention_days, mirroring the request body’s retention.expire_after_days.)

  • enabled (bool) – Whether the schedule is active. A disabled schedule does not run and is not deleted.

  • next_scheduled_run (datetime.datetime | None) – When the next backup is planned, or None. None iff enabled is False: disabling clears the pending run, and re-enabling recomputes it from the moment of the update, so a disable/re-enable cycle shifts the cadence rather than resuming the old slot.

  • created_at (datetime.datetime) – When the schedule was created.

Parameters:
  • schedule_id (str)

  • name (str)

  • index_id (str)

  • project_id (str)

  • schedule_type (str)

  • frequency (str)

  • retention_expire_after_days (int)

  • enabled (bool)

  • created_at (datetime)

  • next_scheduled_run (datetime | None)

Note

Only one enabled schedule may exist per index. Creating a second one raises ConflictError, telling you to disable or delete the first; re-enabling a disabled schedule while another is enabled fails the same way.

schedule_id: str
name: str
index_id: str
project_id: str
schedule_type: str
frequency: str
retention_expire_after_days: int
enabled: bool
created_at: datetime
next_scheduled_run: datetime | None
to_dict()[source]

Return a dict representation of this schedule.

Returns:

Dictionary with all fields, including next_scheduled_run when it is None. Timestamps are rendered back to RFC 3339 strings (normalised to UTC Z form), so the result is JSON-serialisable.

Return type:

dict[str, Any]

Examples

>>> from datetime import datetime, timezone
>>> from pinecone.models.backups.schedules import BackupScheduleModel
>>> schedule = BackupScheduleModel(
...     schedule_id="sched-1",
...     name="daily-compliance-backup",
...     index_id="idx-1",
...     project_id="proj-1",
...     schedule_type="time-based",
...     frequency="daily",
...     retention_expire_after_days=90,
...     enabled=False,
...     created_at=datetime(2026, 4, 2, 18, 22, 56, tzinfo=timezone.utc),
... )
>>> schedule.to_dict()["created_at"]
'2026-04-02T18:22:56Z'
>>> schedule.to_dict()["next_scheduled_run"] is None
True
class pinecone.models.backups.list.BackupScheduleList(schedules, *, pagination=None)[source]

Bases: object

One page of an index’s backup schedules, plus its next-page token.

Returned by list(); not constructed directly. Iteration, len(), names() and enabled_schedules() all read the page in hand only — iter_schedules() walks every page instead.

Parameters:
__init__(schedules, *, pagination=None)[source]

Initialize a BackupScheduleList.

Parameters:
  • schedules (list[BackupScheduleModel]) – List of BackupScheduleModel instances representing the backup schedules on an index.

  • pagination (Pagination | None) – Optional Pagination token for fetching additional pages of results.

Return type:

None

property data: list[BackupScheduleModel]

Return the list of backup schedules.

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of schedule dicts, each produced by BackupScheduleModel.to_dict(). When the wrapper has a pagination token, the dict also includes a "pagination" key with the token for fetching the next page.

Return type:

dict[str, Any]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> schedules = pc.backup_schedules.list(index_name="product-search")
>>> schedules.to_dict()["data"][0]["frequency"]
'daily'
names()[source]

Return the schedule names.

Returns:

Schedule names, in the order the API returned them.

Return type:

list[str]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> pc.backup_schedules.list(index_name="product-search").names()
['compliance-snapshots']
enabled_schedules()[source]

Return only the enabled schedules on this page.

At most one schedule per index can be enabled, so this answers “which schedule is actually running” — as long as the listing fits one page.

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> schedules = pc.backup_schedules.list(index_name="product-search")
>>> [s.name for s in schedules.enabled_schedules()]
['compliance-snapshots']
Return type:

list[BackupScheduleModel]

class pinecone.models.backups.schedules.BackupScheduleHistoryItem(*, backup_id, source_index_id, source_index_name, status, cloud, region, created_at, scheduled_execution_at=None, name=None, description=None, schema=None, record_count=None, namespace_count=None, size_bytes=None, tags=None)[source]

Bases: Struct

One backup produced, or planned, by a schedule.

Returned by history() and its iterator twin; not constructed directly. History rows describe backup snapshots, not the schedule itself, and a row appears as soon as a run is planned, so the list mixes runs that have not happened yet with ones that have.

Variables:
  • backup_id (str) – Unique identifier for the backup snapshot.

  • source_index_id (str) – Identifier of the index that was backed up.

  • source_index_name (str) – Name of the index that was backed up.

  • status (str) – Lifecycle status of the snapshot – "Scheduled" (planned, not yet started), "Initializing", "Ready", or "InitializationFailed". Left as a plain str so a value the SDK has not seen before still decodes.

  • cloud (str) – Cloud provider where the snapshot is stored.

  • region (str) – Cloud region where the snapshot is stored.

  • created_at (datetime.datetime) – When the backup record was created – which for a Scheduled row is when the run was planned, not when data was captured.

  • scheduled_execution_at (datetime.datetime | None) – When the run is planned to happen. Present when status is "Scheduled"; None once the run has started, and None on servers that do not report it.

  • name (str | None) – Name of the snapshot, generated as "{schedule name}-{run timestamp}".

  • description (str | None) – Description of the snapshot, or None.

  • schema (pinecone.models.indexes.schema.IndexSchema | None) – Schema captured from the source index, or None when the server reports none. Metadata-only schemas from older indexes decode to LegacyMetadataField entries.

  • record_count (int | None) – Records in the snapshot. 0 for a Scheduled row – nothing has been captured yet.

  • namespace_count (int | None) – Namespaces in the snapshot.

  • size_bytes (int | None) – Approximate stored size of the snapshot, in bytes.

  • tags (dict[str, Any] | None) – Tags carried over from the source index, or None (the API sends null rather than {} when there are none).

Parameters:

Note

name, record_count, namespace_count and size_bytes can each be absent from a history row even though the API documents them as required, so they are typed as optional here and can come back None. Guard on them rather than assuming a value.

backup_id: str
source_index_id: str
source_index_name: str
status: str
cloud: str
region: str
created_at: datetime
scheduled_execution_at: datetime | None
name: str | None
description: str | None
schema: IndexSchema | None
record_count: int | None
namespace_count: int | None
size_bytes: int | None
tags: dict[str, Any] | None
property is_scheduled: bool

Whether this row is a planned run that has not started yet.

to_dict()[source]

Return a dict representation of this history row.

Returns:

Dictionary with all fields, including optional ones that are None. Timestamps are rendered back to RFC 3339 strings (normalised to UTC Z form), schema becomes a plain dict with the SDK’s internal untyped-field tag stripped, and the result is JSON-serialisable.

Return type:

dict[str, Any]

class pinecone.models.backups.list.BackupScheduleHistoryList(items, *, pagination=None)[source]

Bases: object

One page of the backups a schedule has produced, plus its next-page token.

Returned by history(); not constructed directly. Iteration, len() and scheduled() all read the page in hand only — iter_history() walks every page instead.

Parameters:
__init__(items, *, pagination=None)[source]

Initialize a BackupScheduleHistoryList.

Parameters:
  • items (list[BackupScheduleHistoryItem]) – List of BackupScheduleHistoryItem instances representing backups produced by one schedule.

  • pagination (Pagination | None) – Optional Pagination token for fetching additional pages of results.

Return type:

None

property data: list[BackupScheduleHistoryItem]

Return the list of history rows.

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of history-row dicts, each produced by BackupScheduleHistoryItem.to_dict(). When the wrapper has a pagination token, the dict also includes a "pagination" key with the token for fetching the next page.

Return type:

dict[str, Any]

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> runs = pc.backup_schedules.history(
...     schedule_id="e88f7273-42aa-47e9-af73-593827136867"
... )
>>> runs.to_dict()["data"][0]["status"]
'Scheduled'
scheduled()[source]

Return only the rows for runs that have not started yet.

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> runs = pc.backup_schedules.history(
...     schedule_id="e88f7273-42aa-47e9-af73-593827136867"
... )
>>> [r.backup_id for r in runs.scheduled()]
['b2c3d4e5-f6a7-8901-bcde-f12345678901']
Return type:

list[BackupScheduleHistoryItem]

class pinecone.models.backups.schedules.CreateBackupScheduleRequest(*, name, frequency, retention_days)[source]

Bases: Struct

Request model for creating a backup schedule.

Takes flat keyword arguments and builds the nested request body in to_wire(), filling in schedule.type rather than making every caller repeat the one value the SDK sends.

Variables:
  • name (str) – Name for the schedule (required). Produced backups are named "{name}-{run timestamp}".

  • frequency (str) – Cadence (required), one of "daily", "weekly", "monthly". Validated on construction.

  • retention_days (int) – Days to retain each backup this schedule produces (required). Must be at least 1, which is checked here; the maximum is a per-project setting enforced server-side. Serialised as retention.expire_after_days.

Raises:

ValueError – If frequency is not a supported cadence, or retention_days is less than 1.

Parameters:
  • name (str)

  • frequency (str)

  • retention_days (int)

Examples

>>> from pinecone.models.backups.schedules import CreateBackupScheduleRequest
>>> request = CreateBackupScheduleRequest(
...     name="daily-compliance-backup", frequency="daily", retention_days=90
... )
>>> request.to_wire() == {
...     "name": "daily-compliance-backup",
...     "schedule": {"type": "time-based", "frequency": "daily"},
...     "retention": {"expire_after_days": 90},
... }
True
name: str
frequency: str
retention_days: int
to_wire()[source]

Return the nested JSON body the create-schedule endpoint expects.

This is the encoding entry point for this model: the flat fields do not match the wire shape, so encode to_wire() rather than the struct itself.

Return type:

dict[str, Any]

class pinecone.models.backups.schedules.UpdateBackupScheduleRequest(*, frequency=None, retention_days=None, enabled=None)[source]

Bases: Struct

Request model for updating an existing backup schedule.

Every field is optional; omitted fields are left unchanged. Like CreateBackupScheduleRequest, this takes flat keyword arguments and builds the nested body in to_wire(), which emits only the fields you set. A request with nothing set encodes to {} and is a no-op server-side.

The schedule’s name cannot be changed, and neither can the index it is attached to – the API exposes no field for either.

Variables:
  • frequency (str | None) – New cadence, one of "daily", "weekly", "monthly", or None to leave it unchanged.

  • retention_days (int | None) – New retention window in days, or None to leave it unchanged. Must be at least 1; serialised as retention.expire_after_days. Changing it also re-times the pending deletions of backups this schedule already produced.

  • enabled (bool | None) – False to disable the schedule (clearing its next_scheduled_run), True to re-enable it, or None to leave it unchanged. Re-enabling enqueues a new backup and recomputes the next run from now, so it is not a free toggle; it also raises ConflictError if another schedule on the same index is already enabled.

Raises:

ValueError – If frequency is set to an unsupported cadence, or retention_days is set to less than 1.

Parameters:
  • frequency (str | None)

  • retention_days (int | None)

  • enabled (bool | None)

Examples

>>> from pinecone.models.backups.schedules import UpdateBackupScheduleRequest
>>> UpdateBackupScheduleRequest(enabled=False).to_wire()
{'enabled': False}
>>> UpdateBackupScheduleRequest(frequency="weekly", retention_days=30).to_wire() == {
...     "frequency": "weekly",
...     "retention": {"expire_after_days": 30},
... }
True
frequency: str | None
retention_days: int | None
enabled: bool | None
to_wire()[source]

Return the sparse nested JSON body the update-schedule endpoint expects.

Only the fields you set appear, so unset fields are left unchanged server-side rather than being reset to a default.

Return type:

dict[str, Any]

Namespace Models

class pinecone.models.namespaces.models.NamespaceDescription(*, name='', record_count=0, schema=None, indexed_fields=None, size_bytes=0)[source]

Bases: StructDictMixin, Struct

One namespace: its name, how much is in it, and which fields it indexes.

Variables:
  • name (str) – The namespace’s name. "" is the default namespace.

  • record_count (int) – Records in the namespace. Eventually consistent, so a record you just wrote may not be counted yet.

  • schema (pinecone.models.namespaces.models.NamespaceSchema | None) – Which metadata fields are indexed for filtering, or None when the namespace has no schema.

  • indexed_fields (pinecone.models.namespaces.models.IndexedFields | None) – The same field names without the per-field configuration, or None.

  • size_bytes (int) – The total size of the namespace’s data, in bytes. This is an approximation, not an exact byte count: data written before size tracking was enabled reads as 0, and recently deleted data may still be counted until compaction converges the value. Defaults to 0, which also covers responses that omit the field entirely — a 0 therefore does not by itself mean the namespace is empty.

Parameters:
name: str
record_count: int
schema: NamespaceSchema | None
indexed_fields: IndexedFields | None
size_bytes: int
class pinecone.models.namespaces.models.ListNamespacesResponse(*, namespaces=<factory>, pagination=None, total_count=0)[source]

Bases: StructDictMixin, Struct

One page of namespace descriptions.

Iterable and sized directly, so for ns in response and len(response) walk this page. total_count counts every matching namespace, not just this page, so compare the two to tell whether more pages remain — or just follow pagination until it is None.

Variables:
Parameters:

See also

Pagination — the paging loop used across the SDK.

namespaces: list[NamespaceDescription]
pagination: Pagination | None
total_count: int
class pinecone.models.namespaces.models.NamespaceSchema(*, fields=<factory>)[source]

Bases: StructDictMixin, Struct

Which metadata fields a namespace indexes for filtering.

Variables:

fields (dict[str, pinecone.models.namespaces.models.NamespaceFieldConfig]) – Field name to its NamespaceFieldConfig. A field absent here is stored but cannot be filtered on.

Parameters:

fields (dict[str, NamespaceFieldConfig])

fields: dict[str, NamespaceFieldConfig]
class pinecone.models.namespaces.models.NamespaceFieldConfig(*, filterable=False)[source]

Bases: StructDictMixin, Struct

Whether one metadata field is indexed for filtering.

filterable defaults to False only so a response decodes when the server omits the flag. As a request value False is rejected — the only accepted value is True. To leave a field unindexed, omit it from fields rather than sending filterable=False.

Variables:

filterable (bool) – Whether the field is indexed and can appear in a filter.

Parameters:

filterable (bool)

filterable: bool
class pinecone.models.namespaces.models.IndexedFields(*, fields=<factory>)[source]

Bases: StructDictMixin, Struct

The indexed metadata field names, without the per-field configuration.

Variables:

fields (list[str]) – The names of the fields that can appear in a filter.

Parameters:

fields (list[str])

fields: list[str]

Pagination Models

class pinecone.models.pagination.Page(*, items, pagination_token)[source]

Bases: Generic[T]

One page of results from a paginated listing.

You meet a Page only when walking a listing page by page with Paginator.pages(); iterating a Paginator directly yields the items and hides pages entirely. Not constructed directly.

Variables:
  • items (list) – The results on this page, in the order the server returned them.

  • pagination_token (str | None) – Opaque cursor naming the page after this one, or None when this is the last page. A page truncated by the paginator’s limit also reports None here even though the server had more — resume from Paginator.pagination_token instead.

Parameters:
  • items (list[T])

  • pagination_token (str | None)

Examples

>>> pages = pc.backup_schedules.iter_history(
...     schedule_id="e88f7273-42aa-47e9-af73-593827136867"
... ).pages()
>>> first = next(pages)
>>> len(first.items), first.has_more
(1, True)

See also

Pagination — walking, limiting, and resuming a listing.

__init__(*, items, pagination_token)[source]
Parameters:
  • items (list[T])

  • pagination_token (str | None)

Return type:

None

property has_more: bool

Whether a page follows this one, i.e. whether it carries a token.

class pinecone.models.pagination.Paginator(*, fetch_page, initial_token=None, limit=None)[source]

Bases: Generic[T]

Lazy cursor over a listing endpoint that returns its results in pages.

Returned by the SDK’s sync list methods; not constructed directly. Nothing is requested until you iterate, and each page is fetched only once the previous one runs out, so a listing you stop reading early costs only the pages you actually consumed.

Iterate it directly to get items and never think about pages. Use pages() when the page boundary matters — checkpointing a long walk, or handing each response straight to a batch job. Use to_list() when you want the whole listing in memory at once.

A paginator is re-iterable, and every walk restarts from the token it was built with rather than continuing where the last one stopped.

Parameters:
  • fetch_page (Callable[[str | None], Page[T]]) – Called with a pagination token (None for the first page) and returns the matching Page. Supplied by the list method that built this paginator.

  • initial_token (str | None) – Token to resume from, taken from an earlier walk’s pagination_token; None starts at the first page.

  • limit (int | None) – Stop after this many items across all pages; None walks to the end of the listing.

Examples

>>> for index in pc.indexes.list():
...     print(index.name, index.status.state)

See also

Pagination — the same mechanics with async examples, plus the separate list_paginated interface for vector IDs.

__init__(*, fetch_page, initial_token=None, limit=None)[source]
Parameters:
Return type:

None

property pagination_token: str | None

Cursor for the page after the one most recently fetched.

Persist this to resume the walk in a later process — pass it back as the list method’s pagination_token. It reflects only what has been fetched so far: before you iterate it is whatever token the paginator was built with, and it is None once the walk reaches the last page.

pages()[source]

Walk the listing one Page at a time instead of item by item.

When limit is set, yields whole pages until the remaining budget is smaller than the next page, then yields that page truncated and stops. The truncated page reports pagination_token=None; to carry on later, resume from this paginator’s own pagination_token, which still holds the server’s cursor.

Returns:

Generator of Page, each with an items list and a pagination_token naming the page after it.

Return type:

Generator[Page[T], None, None]

Examples

>>> runs = pc.backup_schedules.iter_history(
...     schedule_id="e88f7273-42aa-47e9-af73-593827136867"
... )
>>> [(len(page.items), page.has_more) for page in runs.pages()]
[(1, True), (1, False)]
to_list()[source]

Walk every remaining page and return all the items in one list.

Every page is fetched before this returns and the whole listing is held in memory, so iterate the paginator instead when the listing is large or you may stop early.

Returns:

list of every item the walk produced, in server order.

Return type:

list[T]

Examples

>>> runs = pc.backup_schedules.iter_history(
...     schedule_id="e88f7273-42aa-47e9-af73-593827136867"
... )
>>> len(runs.to_list())
2
class pinecone.models.pagination.AsyncPaginator(*, fetch_page, initial_token=None, limit=None)[source]

Bases: Generic[T]

Lazy cursor over a paged listing, for use with async for.

What Paginator is on Pinecone, this is on AsyncPinecone: returned by the async list methods, never constructed directly. The list method itself is not a coroutine — it hands back the paginator synchronously, and the awaiting happens as you walk it.

Parameters:
  • fetch_page (Callable[[str | None], Awaitable[Page[T]]]) – Awaitable called with a pagination token (None for the first page), returning the matching Page. Supplied by the list method that built this paginator.

  • initial_token (str | None) – Token to resume from, taken from an earlier walk’s pagination_token; None starts at the first page.

  • limit (int | None) – Stop after this many items across all pages; None walks to the end of the listing.

Examples

from pinecone import AsyncPinecone

async with AsyncPinecone(api_key="your-api-key") as pc:
    async for index in pc.indexes.list():
        print(index.name, index.status.state)

See also

Pagination — walking, limiting, and resuming a listing.

__init__(*, fetch_page, initial_token=None, limit=None)[source]
Parameters:
Return type:

None

property pagination_token: str | None

Cursor for the page after the one most recently fetched.

Persist this to resume the walk in a later process — pass it back as the list method’s pagination_token. It reflects only what has been fetched so far: before you iterate it is whatever token the paginator was built with, and it is None once the walk reaches the last page.

async pages()[source]

Walk the listing one Page at a time instead of item by item.

When limit is set, yields whole pages until the remaining budget is smaller than the next page, then yields that page truncated and stops. The truncated page reports pagination_token=None; to carry on later, resume from this paginator’s own pagination_token, which still holds the server’s cursor.

Returns:

AsyncGenerator of Page, each with an items list and a pagination_token naming the page after it.

Return type:

AsyncGenerator[Page[T], None]

Examples

async with AsyncPinecone(api_key="your-api-key") as pc:
    async for page in pc.indexes.list().pages():
        print(len(page.items), page.has_more)
async to_list()[source]

Walk every remaining page and return all the items in one list.

Every page is fetched before this returns and the whole listing is held in memory, so iterate the paginator instead when the listing is large or you may stop early.

Returns:

list of every item the walk produced, in server order.

Return type:

list[T]

Examples

async with AsyncPinecone(api_key="your-api-key") as pc:
    indexes = await pc.indexes.list().to_list()

Enums

class pinecone.models.enums.CloudProvider(value)[source]

Bases: str, Enum

Public cloud a managed index runs in.

Goes in the cloud key of a managed deployment, and in create_for_model()’s cloud argument. Pair it with a region enum for the same provider — AwsRegion, GcpRegion, or AzureRegion.

AWS = 'aws'
GCP = 'gcp'
AZURE = 'azure'
class pinecone.models.enums.Metric(value)[source]

Bases: str, Enum

How similarity between two dense vectors is scored.

Set on the dense vector field in an index’s schema and fixed for the life of that field. COSINE compares direction and ignores magnitude, which is what most text embedding models are trained for and the right default when in doubt. DOTPRODUCT takes magnitude into account, and is the metric sparse fields always use. EUCLIDEAN scores straight-line distance, so a smaller score is a closer match.

COSINE = 'cosine'
EUCLIDEAN = 'euclidean'
DOTPRODUCT = 'dotproduct'
class pinecone.models.enums.VectorType(value)[source]

Bases: str, Enum

Dense or sparse, for the deprecated single-vector index shape.

Reaches the API only through the deprecated vector_type= argument to create(). A current schema names a dense_vector or sparse_vector field type instead, which is what lets one index hold both.

DENSE = 'dense'
SPARSE = 'sparse'
class pinecone.models.enums.DeletionProtection(value)[source]

Bases: str, Enum

Whether an index refuses to be deleted.

While ENABLED, delete() on the index fails with ForbiddenError, and you have to configure it back to DISABLED first. New indexes are DISABLED.

ENABLED = 'enabled'
DISABLED = 'disabled'
class pinecone.models.enums.EmbedModel(value)[source]

Bases: str, Enum

Known embedding models for integrated indexes.

A convenience enum rather than an exhaustive list: model is also accepted as a plain string, so a model added after this SDK release can still be used. Call list_models() for the models currently available.

Multilingual_E5_Large = 'multilingual-e5-large'
Pinecone_Sparse_English_V0 = 'pinecone-sparse-english-v0'
Llama_Text_Embed_V2 = 'llama-text-embed-v2'
Pinecone_Sparse_Multilingual_V0 = 'pinecone-sparse-multilingual-v0'
class pinecone.models.enums.RerankModel(value)[source]

Bases: str, Enum

Known reranking models.

Like EmbedModel, a convenience enum rather than an exhaustive list.

Note

Pinecone_Rerank_V0 is deprecated and most projects can no longer use it: a request naming it is rejected with a permission error whose message points to a current model. Prefer another member of this enum.

Bge_Reranker_V2_M3 = 'bge-reranker-v2-m3'
Cohere_Rerank_3_5 = 'cohere-rerank-3.5'
Pinecone_Rerank_V0 = 'pinecone-rerank-v0'
class pinecone.models.enums.PodType(value)[source]

Bases: str, Enum

Pod hardware family and size, for the pod_type of a pod deployment.

The family before the dot picks what the pod is optimized for — s1 for storage, p1 for balanced performance, p2 for query throughput — and the xN after it is the size multiplier. See Working with pod-based indexes for what each family trades away. Pod-based indexes predate managed ones; reach for a managed deployment unless you have a reason not to.

P1_X1 = 'p1.x1'
P1_X2 = 'p1.x2'
P1_X4 = 'p1.x4'
P1_X8 = 'p1.x8'
S1_X1 = 's1.x1'
S1_X2 = 's1.x2'
S1_X4 = 's1.x4'
S1_X8 = 's1.x8'
P2_X1 = 'p2.x1'
P2_X2 = 'p2.x2'
P2_X4 = 'p2.x4'
P2_X8 = 'p2.x8'
class pinecone.models.enums.PodIndexEnvironment(value)[source]

Bases: str, Enum

Environments for the environment of a pod deployment.

A pod-based index names one environment instead of a cloud and region pair; the member names encode both. Also a convenience enum rather than an exhaustive list.

US_WEST1_GCP = 'us-west1-gcp'
US_CENTRAL1_GCP = 'us-central1-gcp'
US_WEST4_GCP = 'us-west4-gcp'
US_EAST4_GCP = 'us-east4-gcp'
NORTHAMERICA_NORTHEAST1_GCP = 'northamerica-northeast1-gcp'
ASIA_NORTHEAST1_GCP = 'asia-northeast1-gcp'
ASIA_SOUTHEAST1_GCP = 'asia-southeast1-gcp'
US_EAST1_GCP = 'us-east1-gcp'
EU_WEST1_GCP = 'eu-west1-gcp'
EU_WEST4_GCP = 'eu-west4-gcp'
US_EAST1_AWS = 'us-east-1-aws'
EASTUS_AZURE = 'eastus-azure'
class pinecone.models.enums.AwsRegion(value)[source]

Bases: str, Enum

AWS regions for the region of a managed index on cloud="aws".

A convenience enum rather than an exhaustive list, like EmbedModel: region also accepts a plain string, so a region added after this SDK release still works.

US_EAST_1 = 'us-east-1'
US_WEST_2 = 'us-west-2'
EU_WEST_1 = 'eu-west-1'
EU_CENTRAL_1 = 'eu-central-1'
AP_SOUTHEAST_1 = 'ap-southeast-1'
class pinecone.models.enums.AzureRegion(value)[source]

Bases: str, Enum

Azure regions for the region of a managed index on cloud="azure".

A convenience enum rather than an exhaustive list, like EmbedModel: region also accepts a plain string, so a region added after this SDK release still works.

EASTUS2 = 'eastus2'
GERMANYWESTCENTRAL = 'germanywestcentral'
class pinecone.models.enums.GcpRegion(value)[source]

Bases: str, Enum

GCP regions for the region of a managed index on cloud="gcp".

A convenience enum rather than an exhaustive list, like EmbedModel: region also accepts a plain string, so a region added after this SDK release still works.

US_CENTRAL1 = 'us-central1'
EUROPE_WEST4 = 'europe-west4'

Admin Models

class pinecone.models.admin.api_key.APIKeyModel(*, id, name=None, project_id, roles)[source]

Bases: StructDictMixin, Struct

Response model for a Pinecone API key. The secret is not included.

Variables:
  • id (str) – Unique identifier for the API key. This is what every API-key operation takes as api_key_id, and it is not the secret.

  • name (str | None) – Name of the API key, or None when the backend has no display label set for this key.

  • project_id (str) – Identifier of the project the key belongs to. A key’s authority never reaches outside that project.

  • roles (list[APIKeyRole]) – List of roles assigned to the key (see APIKeyRole).

Parameters:

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> key = admin.api_keys.describe(api_key_id="key-abc123")
>>> key.id
'key-abc123'
>>> key.name
'prod-search-key'
>>> key.roles
[<APIKeyRole.DATA_PLANE_EDITOR: 'DataPlaneEditor'>]

See also

id: str
name: str | None
project_id: str
roles: list[APIKeyRole]
property role: APIKeyRole

Singular alias for roles when the key has exactly one role.

Returns:

The single role assigned to this key.

Return type:

APIKeyRole

Raises:

ValueError – If the key has no roles or more than one role.

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> key = admin.api_keys.describe(api_key_id="key-abc123")
>>> key.role
<APIKeyRole.DATA_PLANE_EDITOR: 'DataPlaneEditor'>

Keys with two or more roles raise ValueError, so reach for this only where a key is known to hold exactly one:

>>> from pinecone.models.admin.api_key import APIKeyModel, APIKeyRole
>>> multi_role_key = APIKeyModel(
...     id="key-def456",
...     name="ci-pipeline-key",
...     project_id="proj-abc123",
...     roles=[APIKeyRole.CONTROL_PLANE_EDITOR, APIKeyRole.DATA_PLANE_EDITOR],
... )
>>> multi_role_key.role
Traceback (most recent call last):
    ...
ValueError: API key has 2 roles; use .roles to access all
class pinecone.models.admin.api_key.APIKeyList(api_keys)[source]

Bases: object

The API keys of one project, as returned by a list call.

A sequence of APIKeyModel — iterable, indexable, and sized — with names() and to_dict() on top. Not constructed directly; it is what ApiKeys.list() returns.

Unlike the organization-wide admin listings, this is not paginated: a project’s keys arrive in one response, so there is no cursor to follow.

Examples

>>> from pinecone.models.admin.api_key import APIKeyList, APIKeyModel, APIKeyRole
>>> keys = APIKeyList(
...     [
...         APIKeyModel(
...             id="key-abc123",
...             name="prod-search-key",
...             project_id="proj-abc123",
...             roles=[APIKeyRole.DATA_PLANE_EDITOR],
...         )
...     ]
... )
>>> keys.names()
['prod-search-key']
Parameters:

api_keys (list[APIKeyModel])

__init__(api_keys)[source]

Initialize an APIKeyList.

Parameters:

api_keys (list[APIKeyModel]) – List of APIKeyModel instances representing Pinecone API keys.

Return type:

None

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of API key dicts, each produced by APIKeyModel.to_dict().

Return type:

dict[str, Any]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> keys = admin.api_keys.list(project_id="proj-abc123")
>>> keys.to_dict()
{'data': [{'name': 'prod-search-key', ...}, {'name': 'ci-pipeline-key', ...}]}
names()[source]

Return a list of API key names.

Returns:

API key names in the same order as the list.

Elements are None for keys whose backend display label is unset.

Return type:

list[str | None]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> keys = admin.api_keys.list(project_id="proj-abc123")
>>> keys.names()
['prod-search-key', 'ci-pipeline-key']
class pinecone.models.admin.api_key.APIKeyWithSecret(*, key, value)[source]

Bases: StructDictMixin, Struct

Response model for an API key together with its secret value.

Returned only by ApiKeys.create(), and the secret it carries is obtainable exactly once — no later request returns it, and there is no rotation for API keys, so a lost secret means creating a replacement key and deleting the old one.

Variables:
  • key (APIKeyModel) – The API key metadata, including the id every other API-key operation takes.

  • value (str) – The secret API key string — what Pinecone is constructed with. Treat as a credential.

Parameters:

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> created = admin.api_keys.create(project_id="proj-abc123", name="prod-search-key")
>>> created.key.id
'key-abc123'

repr() keeps only the last four characters of the secret, so an object logged whole does not leak it:

>>> repr(created).endswith("value='...alue')")
True

Warning

The masking stops at repr(). to_dict() and JSON encoding return value in full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.

key: APIKeyModel
value: str
class pinecone.models.admin.api_key.APIKeyRole(value)[source]

Bases: str, Enum

Roles that can be assigned to a Pinecone API key.

Possible values: PROJECT_EDITOR, PROJECT_VIEWER, CONTROL_PLANE_EDITOR, CONTROL_PLANE_VIEWER, DATA_PLANE_EDITOR, DATA_PLANE_VIEWER.

Every role here is project-scoped: an API key’s authority never reaches beyond the project it was created in. This is a str enum, so the plain role names are accepted interchangeably with the members.

Examples

>>> from pinecone import Admin
>>> from pinecone.models.admin.api_key import APIKeyRole
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> result = admin.api_keys.create(
...     project_id="proj-abc123",
...     name="search-service-key",
...     roles=[APIKeyRole.DATA_PLANE_EDITOR],
... )
>>> result.key.roles
[<APIKeyRole.DATA_PLANE_EDITOR: 'DataPlaneEditor'>]

See also

  • RoleName — the roles used for users, service accounts, and invites. That set includes organization-scoped roles, which an API key cannot hold.

  • ApiKeys.update() — changing a key’s roles replaces the whole set rather than adding to it.

PROJECT_EDITOR = 'ProjectEditor'
PROJECT_VIEWER = 'ProjectViewer'
CONTROL_PLANE_EDITOR = 'ControlPlaneEditor'
CONTROL_PLANE_VIEWER = 'ControlPlaneViewer'
DATA_PLANE_EDITOR = 'DataPlaneEditor'
DATA_PLANE_VIEWER = 'DataPlaneViewer'
class pinecone.models.admin.organization.OrganizationModel(*, id, name, plan, payment_status, created_at, support_tier)[source]

Bases: StructDictMixin, Struct

Response model for a Pinecone organization.

The organization is the top of Pinecone’s hierarchy: projects, users, service accounts, and invites all belong to one. An Admin client’s credentials resolve to exactly one organization, so most admin operations never need this id.

Variables:
  • id (str) – Unique identifier for the organization. Also what an organization-scoped role binding reports as its resource_id.

  • name (str) – Name of the organization.

  • plan (str) – The organization’s plan tier, as the server names it. Which features and roles are available depends on it, so a ForbiddenError naming a plan is about this field.

  • payment_status (str) – Current payment status.

  • created_at (str) – Timestamp when the organization was created.

  • support_tier (str) – Support tier for the organization.

Parameters:

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> org = admin.organizations.describe(organization_id="org-abc123")
>>> org.name
'Acme Corp'
>>> org["plan"]
'Standard'
id: str
name: str
plan: str
payment_status: str
created_at: str
support_tier: str
class pinecone.models.admin.organization.OrganizationList(organizations)[source]

Bases: object

The organizations reachable with the current credentials.

A sequence of OrganizationModel — iterable, indexable, and sized — with names() and to_dict() on top. Not constructed directly; it is what Organizations.list() returns.

This listing is not paginated: the organizations arrive in one response, so there is no cursor to follow.

Examples

>>> from pinecone.models.admin.organization import (
...     OrganizationList,
...     OrganizationModel,
... )
>>> orgs = OrganizationList(
...     [
...         OrganizationModel(
...             id="org-abc123",
...             name="Acme Corp",
...             plan="Standard",
...             payment_status="Active",
...             created_at="2026-01-01T00:00:00Z",
...             support_tier="Standard",
...         )
...     ]
... )
>>> orgs.names()
['Acme Corp']
Parameters:

organizations (list[OrganizationModel])

__init__(organizations)[source]

Initialize an OrganizationList.

Parameters:

organizations (list[OrganizationModel]) – List of OrganizationModel instances representing Pinecone organizations.

Return type:

None

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of organization dicts, each produced by OrganizationModel.to_dict().

Return type:

dict[str, Any]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> orgs = admin.organizations.list()
>>> orgs.to_dict()
{'data': [{'name': 'acme-corp', ...}, {'name': 'research-team', ...}]}
names()[source]

Return a list of organization names.

Returns:

Organization names in the same order as the list.

Return type:

list[str]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> orgs = admin.organizations.list()
>>> orgs.names()
['acme-corp', 'research-team']
class pinecone.models.admin.project.ProjectModel(*, id, name, max_pods, force_encryption_with_cmek, organization_id, created_at=None)[source]

Bases: StructDictMixin, Struct

Response model for a Pinecone project.

A project owns indexes and API keys, and is the finer of the two scopes a role binding can name. Project names are not unique within an organization, so id is the only safe way to refer to one.

Variables:
  • id (str) – Unique identifier for the project. This is the resource_id a project-scoped role binding takes, and the project_id the API-key operations take.

  • name (str) – Name of the project. Not unique — two projects in the same organization can share one.

  • max_pods (int) – Maximum number of pods allowed in the project. Applies to pod-based indexes only; serverless indexes are unaffected.

  • force_encryption_with_cmek (bool) – Whether CMEK encryption is enforced.

  • organization_id (str) – Identifier of the parent organization.

  • created_at (str | None) – Timestamp when the project was created, or None when the server omits it.

Parameters:
  • id (str)

  • name (str)

  • max_pods (int)

  • force_encryption_with_cmek (bool)

  • organization_id (str)

  • created_at (str | None)

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> project = admin.projects.describe(project_id="proj-abc123")
>>> project.name
'my-project'
>>> project.organization_id
'org-abc123'
id: str
name: str
max_pods: int
force_encryption_with_cmek: bool
organization_id: str
created_at: str | None
class pinecone.models.admin.project.ProjectList(projects)[source]

Bases: object

The projects of the organization the credentials resolve to.

A sequence of ProjectModel — iterable, indexable, and sized — with names() and to_dict() on top. Not constructed directly; it is what Projects.list() returns.

This listing is not paginated: the projects arrive in one response, so there is no cursor to follow. Because names are not unique, names() can contain duplicates.

Examples

>>> from pinecone.models.admin.project import ProjectList, ProjectModel
>>> projects = ProjectList(
...     [
...         ProjectModel(
...             id="proj-abc123",
...             name="production-search",
...             max_pods=10,
...             force_encryption_with_cmek=False,
...             organization_id="org-abc123",
...         )
...     ]
... )
>>> projects.names()
['production-search']
Parameters:

projects (list[ProjectModel])

__init__(projects)[source]

Initialize a ProjectList.

Parameters:

projects (list[ProjectModel]) – List of ProjectModel instances representing Pinecone projects.

Return type:

None

to_dict()[source]

Return the list as a serializable dict.

Returns:

A dict with a "data" key containing a list of project dicts, each produced by ProjectModel.to_dict().

Return type:

dict[str, Any]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> projects = admin.projects.list()
>>> projects.to_dict()
{'data': [{'name': 'production-search', ...}, {'name': 'staging-recommendations', ...}]}
names()[source]

Return a list of project names.

Returns:

Project names in the same order as the list.

Return type:

list[str]

Examples

>>> from pinecone import Admin
>>> admin = Admin(client_id="your-client-id", client_secret="your-client-secret")
>>> projects = admin.projects.list()
>>> projects.names()
['production-search', 'staging-recommendations']
class pinecone.models.admin.token.TokenResponse(*, access_token, token_type=None, expires_in=None)[source]

Bases: StructDictMixin, Struct

Response model for the OAuth2 client-credentials token exchange.

Admin performs this exchange itself and refreshes the token as needed, so callers do not normally handle one of these. It is documented because the token is what a service account’s client_id and client_secret are traded for.

Variables:
  • access_token (str) – The Bearer token used to authorize Admin API requests. Treat as a credential.

  • token_type (str | None) – The type of token issued. "Bearer" in practice, and None when the server omits the field.

  • expires_in (int | None) – Seconds until the token expires, or None when the server omits it. Deleting the service account behind the token cuts it short of this; rotating that account’s secret does not — the token already issued stays valid until it expires.

Parameters:
  • access_token (str)

  • token_type (str | None)

  • expires_in (int | None)

Examples

>>> from pinecone.models.admin.token import TokenResponse
>>> token = TokenResponse(
...     access_token="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9", token_type="Bearer"
... )
>>> token["token_type"]
'Bearer'
>>> token.expires_in is None
True

repr() keeps only the last four characters of access_token, so an object logged whole does not leak it:

>>> repr(token).startswith("TokenResponse(access_token='...VCJ9'")
True

Warning

The masking stops at repr(). to_dict() and JSON encoding return access_token in full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.

access_token: str
token_type: str | None
expires_in: int | None
class pinecone.models.admin.pagination.PaginationResponse(*, next=None)[source]

Bases: StructDictMixin, Struct

Cursor envelope returned by paginated Admin API list responses.

Variables:

next (str | None) – Opaque cursor for the next page, or None when the server did not supply one. The value is never parsed or constructed by the SDK — pass it back verbatim as the pagination_token argument on the following list call.

Parameters:

next (str | None)

Examples

>>> from pinecone.models.admin.pagination import PaginationResponse
>>> page = PaginationResponse(next="eyJsYXN0X2lkIjoiZTJlOTI1MjMifQ==")
>>> page.next
'eyJsYXN0X2lkIjoiZTJlOTI1MjMifQ=='
next: str | None
class pinecone.models.admin.user.UserModel(*, id, email, name=None)[source]

Bases: StructDictMixin, Struct

Response model for a user who is a member of the organization.

What the user is allowed to do is not part of this model. Permissions come only from role bindings, so read them through RoleBindings.list() with principal_type="user" and this id as principal_id.

Variables:
  • id (str) – Unique identifier (UUID) for the user. This is the principal_id role-binding queries take, and it is not the ID of the invite the user accepted.

  • email (str) – The user’s email address.

  • name (str | None) – The user’s display name, or None when the user has not set one. The server omits the field entirely in that case.

Parameters:

Examples

>>> from pinecone.models.admin.user import UserModel
>>> user = UserModel(id="e2e92523-85dc-4142-b8c2-e681be8b78df", email="alice@example.com")
>>> user.email
'alice@example.com'
>>> user.name is None
True

See also

  • InviteModel — the same person before they accepted, carrying a separate ID and a status.

id: str
email: str
name: str | None
class pinecone.models.admin.user.UserList(*, data=<factory>, pagination=None)[source]

Bases: Struct

A page of users, plus the cursor for the next page.

One raw page of a user listing. Callers who reach users through Users.list() get a Paginator instead, which follows these cursors for them.

Variables:
  • data (list[UserModel]) – The users on this page.

  • pagination (PaginationResponse | None) – Cursor envelope for the next page, or None on the final page.

Parameters:

Examples

>>> from pinecone.models.admin.user import UserList, UserModel
>>> users = UserList(
...     data=[
...         UserModel(
...             id="e2e92523-85dc-4142-b8c2-e681be8b78df",
...             email="alice@example.com",
...         )
...     ]
... )
>>> len(users)
1
>>> users.has_more
False
>>> users.emails()
['alice@example.com']
data: list[UserModel]
pagination: PaginationResponse | None
property pagination_token: str | None

Opaque cursor for the next page, or None if this is the last page.

property has_more: bool

True when the server supplied a cursor for a further page.

emails()[source]

Return the email addresses on this page, in order.

Return type:

list[str]

to_dict()[source]

Return this page as a serializable dict with data and pagination keys.

Return type:

dict[str, Any]

class pinecone.models.admin.invite.InviteModel(*, id, email, status, expires_at=None, processed_at=None, created_at)[source]

Bases: StructDictMixin, Struct

Response model for an invitation to join the organization.

status is typed as str rather than InviteStatus so a status added by the server after this SDK release surfaces as its raw string instead of raising. Compare against InviteStatus members directly — they are str values.

Variables:
  • id (str) – Unique identifier (UUID) for the invite.

  • email (str) – The email address the invite was sent to.

  • status (str) – One of the InviteStatus values.

  • expires_at (str | None) – RFC 3339 timestamp for when the invite expires if not accepted, or None if it does not expire. Resending an invite pushes this further out; read the new value from the resend response rather than computing it.

  • processed_at (str | None) – RFC 3339 timestamp for when the invite was accepted. None (or omitted by the server) while the invite is still pending or expired.

  • created_at (str) – RFC 3339 timestamp for when the invite was created.

Parameters:
  • id (str)

  • email (str)

  • status (str)

  • expires_at (str | None)

  • processed_at (str | None)

  • created_at (str)

Examples

>>> from pinecone.models.admin.invite import InviteModel, InviteStatus
>>> invite = InviteModel(
...     id="9c8e3528-b9c0-4358-84ce-84c28e91b566",
...     email="newhire@acme.com",
...     status="pending",
...     expires_at="2026-05-21T03:00:00Z",
...     created_at="2026-04-14T20:00:00Z",
... )
>>> invite.status == InviteStatus.PENDING
True
>>> invite.processed_at is None
True

See also

  • UserModel — the member record created when the invite is accepted. The two carry separate IDs, so the invite’s id is not usable as a user ID.

id: str
email: str
status: str
expires_at: str | None
processed_at: str | None
created_at: str
class pinecone.models.admin.invite.InviteList(*, data=<factory>, pagination=None)[source]

Bases: Struct

A page of invites, plus the cursor for the next page.

One raw page of an invite listing. Callers who reach invites through Invites.list() get a Paginator instead, which follows these cursors for them.

Variables:
  • data (list[InviteModel]) – The invites on this page. Accepted invites are never among them; the listing covers pending and expired only.

  • pagination (PaginationResponse | None) – Cursor envelope for the next page, or None on the final page.

Parameters:

Examples

>>> from pinecone.models.admin.invite import InviteList, InviteModel
>>> invites = InviteList(
...     data=[
...         InviteModel(
...             id="9c8e3528-b9c0-4358-84ce-84c28e91b566",
...             email="newhire@acme.com",
...             status="pending",
...             created_at="2026-04-14T20:00:00Z",
...         )
...     ]
... )
>>> invites.emails()
['newhire@acme.com']
data: list[InviteModel]
pagination: PaginationResponse | None
property pagination_token: str | None

Opaque cursor for the next page, or None if this is the last page.

property has_more: bool

True when the server supplied a cursor for a further page.

emails()[source]

Return the invited email addresses on this page, in order.

Return type:

list[str]

to_dict()[source]

Return this page as a serializable dict with data and pagination keys.

Return type:

dict[str, Any]

class pinecone.models.admin.invite.InviteStatus(value)[source]

Bases: str, Enum

The lifecycle status of an organization invite.

Possible values: pending, expired, processed.

List operations return only pending and expired invites; processed is returned only when fetching a single invite by ID.

Examples

>>> from pinecone.models.admin.invite import InviteStatus
>>> InviteStatus.PENDING == "pending"
True
PENDING = 'pending'
EXPIRED = 'expired'
PROCESSED = 'processed'
class pinecone.models.admin.service_account.ServiceAccountModel(*, id, name, client_id, created_at, updated_at)[source]

Bases: StructDictMixin, Struct

Response model for a service account. The OAuth secret is not included.

What the account is allowed to do is not part of this model. Permissions come only from role bindings, so read them through RoleBindings.list() with principal_type="service_account" and this id as principal_id.

Variables:
  • id (str) – Unique identifier (UUID) for the service account. Use this as the path parameter on service account operations and as the principal_id when querying or creating role bindings.

  • name (str) – Short human-readable label set at creation time.

  • client_id (str) – OAuth client ID the service account uses to obtain access tokens. Used only for OAuth token exchange — it is not the service account’s identifier for role bindings, and passing it where id is expected reads back as not found.

  • created_at (str) – RFC 3339 timestamp for when the account was created.

  • updated_at (str) – RFC 3339 timestamp of the most recent metadata update.

Parameters:

Examples

>>> from pinecone.models.admin.service_account import ServiceAccountModel
>>> account = ServiceAccountModel(
...     id="f8a3b2c1-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
...     name="ci-prod",
...     client_id="l3Ow0CmFyc4jOONcwiKUCRqQKN0tiCAn",
...     created_at="2026-04-10T15:23:00Z",
...     updated_at="2026-04-12T09:11:00Z",
... )
>>> account.name
'ci-prod'

See also

id: str
name: str
client_id: str
created_at: str
updated_at: str
class pinecone.models.admin.service_account.ServiceAccountList(*, data=<factory>, pagination=None)[source]

Bases: Struct

A page of service accounts, plus the cursor for the next page.

One raw page of a service-account listing. Callers who reach accounts through ServiceAccounts.list() get a Paginator instead, which follows these cursors for them.

Variables:
  • data (list[ServiceAccountModel]) – The service accounts on this page. None of them carries a client_secret.

  • pagination (PaginationResponse | None) – Cursor envelope for the next page, or None on the final page.

Parameters:

Examples

>>> from pinecone.models.admin.service_account import (
...     ServiceAccountList,
...     ServiceAccountModel,
... )
>>> accounts = ServiceAccountList(
...     data=[
...         ServiceAccountModel(
...             id="f8a3b2c1-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
...             name="ci-prod",
...             client_id="l3Ow0CmFyc4jOONcwiKUCRqQKN0tiCAn",
...             created_at="2026-04-10T15:23:00Z",
...             updated_at="2026-04-10T15:23:00Z",
...         )
...     ]
... )
>>> accounts.names()
['ci-prod']
data: list[ServiceAccountModel]
pagination: PaginationResponse | None
property pagination_token: str | None

Opaque cursor for the next page, or None if this is the last page.

property has_more: bool

True when the server supplied a cursor for a further page.

names()[source]

Return the service account names on this page, in order.

Return type:

list[str]

to_dict()[source]

Return this page as a serializable dict with data and pagination keys.

Return type:

dict[str, Any]

class pinecone.models.admin.service_account.ServiceAccountWithSecret(*, service_account, client_secret)[source]

Bases: StructDictMixin, Struct

Response model for a service account with a newly issued OAuth secret.

Returned only by ServiceAccounts.create() and ServiceAccounts.rotate_secret(), and the secret it carries is obtainable exactly once — nothing can retrieve it afterwards, so capture it before the object goes out of scope.

Variables:
  • service_account (ServiceAccountModel) – The service account metadata, including the id every other service-account operation takes.

  • client_secret (str) – The OAuth client secret. Treat as a credential.

Parameters:

Examples

>>> from pinecone.models.admin.service_account import (
...     ServiceAccountModel,
...     ServiceAccountWithSecret,
... )
>>> created = ServiceAccountWithSecret(
...     service_account=ServiceAccountModel(
...         id="f8a3b2c1-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
...         name="ci-prod",
...         client_id="l3Ow0CmFyc4jOONcwiKUCRqQKN0tiCAn",
...         created_at="2026-04-10T15:23:00Z",
...         updated_at="2026-04-10T15:23:00Z",
...     ),
...     client_secret="8p-kkC23XOWvkCosKq",
... )
>>> created.client_secret
'8p-kkC23XOWvkCosKq'

repr() keeps only the last four characters, so an object logged whole does not leak the secret:

>>> repr(created).endswith("client_secret='...osKq')")
True

Warning

The masking stops at repr(). to_dict() and JSON encoding return client_secret in full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.

service_account: ServiceAccountModel
client_secret: str
class pinecone.models.admin.role_binding.RoleBindingModel(*, id, principal_type, principal_id, resource_type, resource_id, role, created_at)[source]

Bases: StructDictMixin, Struct

Response model for a role binding: a role granted to a principal at a scope.

principal_type, resource_type, and role are typed as str rather than as enums so values the server adds after this SDK release surface as their raw strings instead of raising. Compare against PrincipalType, ResourceType, and RoleName directly — they are str values.

Variables:
  • id (str) – Unique identifier (UUID) for the role binding. This is what RoleBindings.delete() takes — revoking a role is addressed by the binding, never by the principal/scope/role triple.

  • principal_type (str) – One of the PrincipalType values.

  • principal_id (str) – The principal’s UUID.

  • resource_type (str) – One of the ResourceType values.

  • resource_id (str) – The organization or project the binding is scoped to. Always populated, including on organization-scoped bindings whose create request omitted it.

  • role (str) – One of the RoleName values.

  • created_at (str) – RFC 3339 timestamp for when the binding was created. There is no updated timestamp: bindings are immutable, so a role change is a create plus a delete rather than an edit.

Parameters:
  • id (str)

  • principal_type (str)

  • principal_id (str)

  • resource_type (str)

  • resource_id (str)

  • role (str)

  • created_at (str)

Examples

>>> from pinecone.models.admin.role_binding import RoleBindingModel, RoleName
>>> binding = RoleBindingModel(
...     id="9a8e3528-b9c0-4358-84ce-84c28e91b566",
...     principal_type="service_account",
...     principal_id="f8a3b2c1-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
...     resource_type="project",
...     resource_id="a2f7dddb-1597-4eff-9f71-535fde243f58",
...     role="DataPlaneEditor",
...     created_at="2026-04-10T15:23:00Z",
... )
>>> binding.role == RoleName.DATA_PLANE_EDITOR
True
id: str
principal_type: str
principal_id: str
resource_type: str
resource_id: str
role: str
created_at: str
class pinecone.models.admin.role_binding.RoleBindingList(*, data=<factory>, pagination=None)[source]

Bases: Struct

A page of role bindings, plus the cursor for the next page.

One raw page of a role-binding listing. Callers who reach bindings through RoleBindings.list() get a Paginator instead, which follows these cursors for them.

Variables:
Parameters:

Examples

>>> from pinecone.models.admin.role_binding import RoleBindingList, RoleBindingModel
>>> bindings = RoleBindingList(
...     data=[
...         RoleBindingModel(
...             id="9a8e3528-b9c0-4358-84ce-84c28e91b566",
...             principal_type="user",
...             principal_id="e2e92523-85dc-4142-b8c2-e681be8b78df",
...             resource_type="organization",
...             resource_id="4f6a1e0c-8f2b-4c1a-9d3e-1b2c3d4e5f60",
...             role="OrgMember",
...             created_at="2026-04-10T15:23:00Z",
...         )
...     ]
... )
>>> bindings.roles()
['OrgMember']
data: list[RoleBindingModel]
pagination: PaginationResponse | None
property pagination_token: str | None

Opaque cursor for the next page, or None if this is the last page.

property has_more: bool

True when the server supplied a cursor for a further page.

roles()[source]

Return the role names on this page, in order.

Return type:

list[str]

to_dict()[source]

Return this page as a serializable dict with data and pagination keys.

Return type:

dict[str, Any]

class pinecone.models.admin.role_binding.RoleBindingInput(*, resource_type, role, resource_id=None)[source]

Bases: StructDictMixin, Struct

A role to grant when creating an invite or a service account.

Unlike the response models, this is an input the SDK sends, so resource_type and role are validated on construction against the values this SDK release knows about.

resource_type selects the binding scope. For organization scope, omit resource_id — the binding applies to the organization inferred from the request context. For project scope, resource_id is required and must be the project UUID.

Variables:
  • resource_type (str) – One of the ResourceType values.

  • role (str) – One of the RoleName values.

  • resource_id (str | None) – The project UUID for project scope; leave unset for organization scope.

Raises:

PineconeValueError – If resource_type or role is not a recognized value, or if resource_type is project and resource_id is missing or empty. Raised at construction, so a malformed binding fails before the call that would have sent it.

Parameters:
  • resource_type (str)

  • role (str)

  • resource_id (str | None)

Examples

>>> from pinecone.models.admin.role_binding import (
...     ResourceType,
...     RoleBindingInput,
...     RoleName,
... )
>>> RoleBindingInput(
...     resource_type=ResourceType.ORGANIZATION, role=RoleName.ORG_MEMBER
... ).to_dict()
{'resource_type': 'organization', 'role': 'OrgMember', 'resource_id': None}

Project-scoped bindings need the project UUID:

>>> RoleBindingInput(
...     resource_type="project",
...     role="ProjectViewer",
...     resource_id="a2f7dddb-1597-4eff-9f71-535fde243f58",
... ).resource_id
'a2f7dddb-1597-4eff-9f71-535fde243f58'

See also

  • RoleBindingModel — what the server returns. This input type names only the scope and the role; the response adds the binding’s own id and the principal.

  • RoleBindings.create() — grants a role to an existing principal, taking the same fields as keyword arguments rather than as this struct.

resource_type: str
role: str
resource_id: str | None
class pinecone.models.admin.role_binding.RoleName(value)[source]

Bases: str, Enum

A role that can be assigned to a principal at a resource scope.

Organization-scoped roles: OrgOwner, OrgManager, OrgMember, OrgBillingAdmin. Project-scoped roles: ProjectOwner, ProjectManager, ProjectMember, ProjectEditor, ProjectViewer, ControlPlaneEditor, ControlPlaneViewer, DataPlaneEditor, DataPlaneViewer.

Membership in this enum only means the SDK will forward the value. Which of these roles may be bound to which scope and principal type, and which the organization’s plan includes, is the server’s decision and is reported as ForbiddenError at bind time.

Examples

>>> from pinecone.models.admin.role_binding import RoleName
>>> RoleName.DATA_PLANE_EDITOR == "DataPlaneEditor"
True
ORG_OWNER = 'OrgOwner'
ORG_MANAGER = 'OrgManager'
ORG_MEMBER = 'OrgMember'
ORG_BILLING_ADMIN = 'OrgBillingAdmin'
PROJECT_OWNER = 'ProjectOwner'
PROJECT_MANAGER = 'ProjectManager'
PROJECT_MEMBER = 'ProjectMember'
PROJECT_EDITOR = 'ProjectEditor'
PROJECT_VIEWER = 'ProjectViewer'
CONTROL_PLANE_EDITOR = 'ControlPlaneEditor'
CONTROL_PLANE_VIEWER = 'ControlPlaneViewer'
DATA_PLANE_EDITOR = 'DataPlaneEditor'
DATA_PLANE_VIEWER = 'DataPlaneViewer'
class pinecone.models.admin.role_binding.PrincipalType(value)[source]

Bases: str, Enum

The kind of principal that receives permissions from a role binding.

Possible values: user, service_account, api_key, invite.

Examples

>>> from pinecone.models.admin.role_binding import PrincipalType
>>> PrincipalType.SERVICE_ACCOUNT == "service_account"
True
USER = 'user'
SERVICE_ACCOUNT = 'service_account'
API_KEY = 'api_key'
INVITE = 'invite'
class pinecone.models.admin.role_binding.ResourceType(value)[source]

Bases: str, Enum

The kind of resource scope a role binding applies to.

Possible values: organization, project.

Examples

>>> from pinecone.models.admin.role_binding import ResourceType
>>> ResourceType.PROJECT == "project"
True
ORGANIZATION = 'organization'
PROJECT = 'project'

Assistant Models

class pinecone.models.assistant.model.AssistantModel(*, name, status, metadata=None, instructions=None, host=None, region=None, created_at=None, updated_at=None)[source]

Bases: AssistantModelLegacyMethodsMixin, StructDictMixin, Struct

Response model for a Pinecone assistant.

Variables:
  • name (str) – The name of the assistant.

  • status (str) – Current status of the assistant (e.g. "Initializing", "Ready", "Terminating", "Terminated", "InitializationFailed").

  • created_at (str | None) – ISO 8601 timestamp when the assistant was created, or None if not returned by the API.

  • updated_at (str | None) – ISO 8601 timestamp when the assistant was last updated, or None if not returned by the API.

  • metadata (dict[str, Any] | None) – Optional metadata dictionary associated with the assistant, or None if not set.

  • instructions (str | None) – Optional description or directive for the assistant to apply to all responses, or None if not set.

  • host (str | None) – The host where the assistant is deployed, or None if not yet available.

  • region (str | None) – The region the assistant is deployed in ("us" or "eu"), or None if not returned by the API.

Parameters:
  • name (str)

  • status (str)

  • metadata (dict[str, Any] | None)

  • instructions (str | None)

  • host (str | None)

  • region (str | None)

  • created_at (str | None)

  • updated_at (str | None)

name: str
status: str
metadata: dict[str, Any] | None
instructions: str | None
host: str | None
region: str | None
created_at: str | None
updated_at: str | None
class pinecone.models.assistant.file_model.AssistantFileModel(*, name, id, metadata=None, created_on=None, updated_on=None, status=None, size=None, multimodal=None, signed_url=None, content_hash=None)[source]

Bases: StructDictMixin, Struct

Response model for a file attached to a Pinecone assistant.

Variables:
  • name (str) – The name of the file.

  • id (str) – Unique identifier for the file. On 2026-07 this may be a user-provided identifier, so it is not guaranteed to be a UUID.

  • metadata (dict[str, object] | None) – Optional metadata dictionary associated with the file, or None if not set.

  • created_on (str | None) – ISO 8601 timestamp when the file was created, or None.

  • updated_on (str | None) – ISO 8601 timestamp when the file was last updated, or None.

  • status (str | None) – Current status of the file (e.g. "Processing", "Available", "Deleting", "ProcessingFailed"), or None.

  • size (int | None) – Size of the file in bytes, or None.

  • multimodal (bool | None) – Whether the file was processed as multimodal, or None.

  • signed_url (str | None) – A temporary signed URL for downloading the file, or None when not requested or unavailable.

  • content_hash (str | None) – Hash of the file content (wire key crc32c_hash), or None when not available. Legacy callers can also access this value via the crc32c_hash property alias.

Parameters:
  • name (str)

  • id (str)

  • metadata (dict[str, object] | None)

  • created_on (str | None)

  • updated_on (str | None)

  • status (str | None)

  • size (int | None)

  • multimodal (bool | None)

  • signed_url (str | None)

  • content_hash (str | None)

percent_done and error_message were removed in the 2026-07 API; accessing them raises an AttributeError naming describe_operation as the replacement.

name: str
id: str
metadata: dict[str, object] | None
created_on: str | None
updated_on: str | None
status: str | None
size: int | None
multimodal: bool | None
signed_url: str | None
content_hash: str | None
property crc32c_hash: str | None

Backwards-compatibility alias for content_hash.

class pinecone.models.assistant.list.ListAssistantsResponse(*, assistants, pagination=None)[source]

Bases: StructDictMixin, Struct

One page of assistants, plus the token for the next one.

Returned by list_page(). This is one page only — pass next back as pagination_token to advance, or call list(), which drives that loop for you and yields assistants directly.

Variables:
Parameters:

Examples

next is None on the last page, which is the loop’s exit condition:

>>> page = pc.assistants.list_page(page_size=10)
>>> page.next is None
True

See also

Pagination — the continuation-token loop, and the paginator that drives it for you.

assistants: list[AssistantModel]
pagination: _Pagination | None
property next: str | None

Token for the next page, or None when this is the last one.

Pass a non-None value back as the pagination_token argument of the same *_page method to fetch the following page.

property next_token: str | None

Alias for next. Prefer next in new code.

class pinecone.models.assistant.list.ListFilesResponse(*, files, pagination=None)[source]

Bases: StructDictMixin, Struct

One page of an assistant’s files, plus the token for the next one.

Returned by list_files_page(). This is one page only — pass next back as pagination_token to advance, or call list_files(), which drives that loop for you and yields files directly.

Variables:
Parameters:

Examples

A newly uploaded file appears here with status "Processing" before it becomes "Available", so filter on it before treating a file as searchable:

page = pc.assistants.list_files_page(
    assistant_name="acme-support-bot",
    page_size=10,
)
for file in page.files:
    print(file.name, file.status)

See also

Pagination — the continuation-token loop, and the paginator that drives it for you.

files: list[AssistantFileModel]
pagination: _Pagination | None
property next: str | None

Token for the next page, or None when this is the last one.

Pass a non-None value back as the pagination_token argument of the same *_page method to fetch the following page.

property next_token: str | None

Alias for next. Prefer next in new code.

class pinecone.models.assistant.operation.OperationModel(*, operation_id, status, operation_type=None, file_id=None, created_at=None, completed_on=None, percent_complete=None, error=None, ingestion_units=None)[source]

Bases: StructDictMixin, Struct

Response model for a long-running assistant operation.

Returned by the file endpoints that start an operation (POST /files/{assistant_name}, PUT /files/{assistant_name}/{file_id}, DELETE /files/{assistant_name}/{file_id}) and by the operations endpoints (GET /operations/{assistant_name}/{operation_id}, GET /operations/{assistant_name}).

The API uses id, created_on and error_message; the rename mapping presents them as operation_id, created_at and error in Python for clarity. Every other attribute carries its wire name.

Every field except operation_id and status is optional so that the smaller body shipped by the 2026-04 upsert path still decodes. The server omits completed_on, error_message and ingestion_units while they do not apply; a spec-conformant server may instead send them as null. Both decode to None.

Variables:
  • operation_id (str) – Unique identifier for the operation (JSON field: id).

  • status (str) – Current status of the operation: "Processing" while it is in progress, "Completed" when it finished successfully, "Failed" when it did not (see error).

  • operation_type (str | None) – The kind of action this operation represents — "upload_file", "upsert_file", "update_file_metadata" or "delete_file" — or None when the server did not report one.

  • file_id (str | None) – Identifier of the file being operated on, or None.

  • created_at (str | None) – ISO 8601 timestamp when the operation was created, or None (JSON field: created_on).

  • completed_on (str | None) – ISO 8601 timestamp when the operation completed or failed, or None while status is "Processing".

  • percent_complete (int | None) – Progress of the operation as a percentage from 0 to 100, or None when the server did not report progress.

  • error (str | None) – Error message if the operation failed, or None (JSON field: error_message). Goes stale across a retry: the backend writes this column with COALESCE, so it is never cleared once set — a retried operation that is back to "Processing", or that eventually succeeds, still carries the earlier attempt’s text. Read it only when status is "Failed".

  • ingestion_units (float | None) – Ingestion units consumed by this operation, reported once a file ingestion operation has completed, or None.

Parameters:
  • operation_id (str)

  • status (str)

  • operation_type (str | None)

  • file_id (str | None)

  • created_at (str | None)

  • completed_on (str | None)

  • percent_complete (int | None)

  • error (str | None)

  • ingestion_units (float | None)

operation_id: str
status: str
operation_type: str | None
file_id: str | None
created_at: str | None
completed_on: str | None
percent_complete: int | None
error: str | None
ingestion_units: float | None
class pinecone.models.assistant.list.ListOperationsResponse(*, operations, pagination=None)[source]

Bases: StructDictMixin, Struct

One page of an assistant’s operations, plus the token for the next one.

Returned by list_operations_page(). This is one page only — pass next back as pagination_token to advance, or call list_operations(), which drives that loop for you and yields operations directly.

Variables:
Parameters:

Examples

Operations are where file-processing progress and failure detail live, so this is the list to check when an upload has not become "Available":

page = pc.assistants.list_operations_page(
    assistant_name="acme-support-bot",
    page_size=10,
)
for operation in page.operations:
    print(operation.operation_id, operation.status)
    if operation.status == "Failed":
        print(operation.error)

See also

Pagination — the continuation-token loop, and the paginator that drives it for you.

operations: list[OperationModel]
pagination: _Pagination | None
property next: str | None

Token for the next page, or None when this is the last one.

Pass a non-None value back as the pagination_token argument of the same *_page method to fetch the following page.

property next_token: str | None

Alias for next. Prefer next in new code.

class pinecone.models.assistant.message.Message(*, content, role='user')[source]

Bases: StructDictMixin, Struct

A message to send to an assistant.

Variables:
  • content (str) – The text content of the message. Must not be blank — the backend trims before checking, so "" and a whitespace-only string alike come back 400 "Message content cannot be empty".

  • role (str) – The role of the message author. Defaults to "user". The backend accepts only the exact strings "user" and "assistant", compared case-sensitively: "User" is rejected with 400 "Role 'User' is not valid", and "" with 400 "Role cannot be empty". Neither field is validated client-side.

Parameters:
content: str
role: str
classmethod from_dict(d)[source]

Create a Message from a dictionary.

Extracts "content" and "role" keys, defaulting role to "user" when not present.

Parameters:

d (Mapping[str, Any]) – A dictionary with at least a "content" key.

Returns:

A new Message instance.

Return type:

Message

Assistant Chat Models

pc.assistants.chat() returns a ChatResponse; pc.assistants.chat_completions() returns the OpenAI-shaped ChatCompletionResponse.

class pinecone.models.assistant.chat.ChatResponse(*, id, model, usage, message, finish_reason, citations, context_snippet_count=None, content_filter_results=None)[source]

Bases: StructDictMixin, Struct

The generated answer to a chat request, with its citations.

Returned by chat() when stream is left False. The answer text is at response.message.content, and the sources come back as structured objects rather than markers woven into that text — which is what a caller needs to render source links. The full path is response.citations[i].references[j].file.name, with citations[i].position saying where in the answer each citation belongs.

Variables:
  • id (str) – Identifier of this chat response.

  • model (str) – Name of the model that generated the answer, which need not be the name you requested.

  • usage (pinecone.models.assistant.chat.ChatUsage) – ChatUsage token counts for the request.

  • message (pinecone.models.assistant.chat.ChatMessage) – The assistant’s reply as a ChatMessage; the text is at message.content.

  • finish_reason (str) – Why generation stopped: "stop" (the model finished), "length" (the token limit was reached), "content_filter" (content filtering rules blocked the output), or "tool_calls" (a tool call was triggered). The literal string "null" also reaches callers, so treat this as an open set of strings rather than switching exhaustively on the four above.

  • citations (list[pinecone.models.assistant.chat.ChatCitation]) – The ChatCitation entries tying positions in message.content to source documents. Empty when the answer drew on no file.

  • context_snippet_count (int | None) – Number of retrieved context snippets that were provided to the model, or None if the server did not report it. 0 means no relevant context was found for the query, which explains an answer with no citations.

  • content_filter_results (dict[str, Any] | None) – Safety classifications reported by the LLM provider, or None when the provider returned none. Read spec for the provider’s name and results for a payload whose shape that provider defines.

Parameters:

Examples

The answer is one string, and each citation names a position in it together with the documents backing the claim at that position:

>>> response = pc.assistants.chat(
...     assistant_name="acme-support-bot",
...     messages=[{"content": "Which regions support BYOC?"}],
... )
>>> response.message.content
'BYOC is available in aws us-east-1.'
>>> citation = response.citations[0]
>>> citation.position
34
>>> citation.references[0].file.name
'q3-revenue-review.pdf'
>>> citation.references[0].pages
[3]
>>> citation.references[0].highlight is None
True

That last line is the default: pass include_highlights=True to chat() to get the source passage as well as the file name.

See also

  • ContextResponse — the retrieved snippets with no answer generated over them, from context(). Use that when you want to run your own model over Pinecone’s retrieval.

  • ChatCompletionResponse — the same answer in the OpenAI-compatible shape, without structured citations.

  • ChatStream — the same answer delivered as chunks, from chat(..., stream=True).

id: str
model: str
usage: ChatUsage
message: ChatMessage
finish_reason: str
citations: list[ChatCitation]
context_snippet_count: int | None
content_filter_results: dict[str, Any] | None
class pinecone.models.assistant.chat.ChatMessage(*, role, content)[source]

Bases: StructDictMixin, Struct

The assistant’s reply inside a ChatResponse.

Reached as response.message. To send a message, build a Message instead — this class only comes back from the API.

Variables:
  • role (str) – The role of the message author (e.g. "user", "assistant").

  • content (str) – The answer text. Citation positions index into this string.

Parameters:
role: str
content: str
class pinecone.models.assistant.chat.ChatCitation(*, position, references)[source]

Bases: StructDictMixin, Struct

A point in the answer, tied to the documents that support it.

Reached as an entry of response.citations on a ChatResponse, or as chunk.citation on a StreamCitationChunk.

Variables:
  • position (int) – Character position in response.message.content that this citation annotates. Insert a footnote marker there to render the answer with inline sources.

  • references (list[pinecone.models.assistant.chat.ChatReference]) – The ChatReference entries supporting the answer at that position. Can hold more than one document.

Parameters:
position: int
references: list[ChatReference]
class pinecone.models.assistant.chat.ChatReference(*, file, pages=None, highlight=None)[source]

Bases: StructDictMixin, Struct

One source document behind a citation.

Reached as an entry of citation.references. These three fields are what a RAG caller renders as a source link.

Variables:
Parameters:
file: AssistantFileModel
pages: list[int] | None
highlight: ChatHighlight | None
class pinecone.models.assistant.chat.ChatHighlight(*, type, content)[source]

Bases: StructDictMixin, Struct

The passage of a source document that a citation drew on.

Reached as reference.highlight, and present only when the chat request set include_highlights=True. Render it to show the reader the source text behind a citation without fetching the file.

Variables:
  • type (str) – The kind of highlighted content (e.g. "text").

  • content (str) – The highlighted passage, taken from the source document.

Parameters:
type: str
content: str
class pinecone.models.assistant.chat.ChatUsage(*, prompt_tokens, completion_tokens, total_tokens)[source]

Bases: StructDictMixin, Struct

Token counts the API reported for one assistant request.

Reached as usage on ChatResponse, ChatCompletionResponse, ContextResponse, AlignmentResult, and on the closing chunk of a stream.

Variables:
  • prompt_tokens (int) – Tokens counted in the prompt.

  • completion_tokens (int) – Tokens counted in the generated answer.

  • total_tokens (int) – Total the API reported for the request.

Parameters:
  • prompt_tokens (int)

  • completion_tokens (int)

  • total_tokens (int)

prompt_tokens: int
completion_tokens: int
total_tokens: int
classmethod from_dict(d)[source]

Build a ChatUsage from a plain dict.

Parameters:

d (dict[str, Any]) – Mapping with any of prompt_tokens, completion_tokens, and total_tokens. A missing key becomes 0 rather than raising, so a partial payload yields a partial count.

Returns:

ChatUsage with the three counts filled in.

Return type:

ChatUsage

class pinecone.models.assistant.chat.ChatCompletionResponse(*, id, model, usage, choices)[source]

Bases: StructDictMixin, Struct

The generated answer to a chat request, in OpenAI-compatible shape.

Returned by chat_completions() when stream is left False. The answer text is nested at response.choices[0].message.content. There is no structured citation list here; citations arrive woven into the answer text, so prefer ChatResponse unless you are pointing existing OpenAI client code at Pinecone.

Variables:
Parameters:

Examples

The text is two levels down, under choices, and there is no citations attribute to read — that absence is the whole difference from ChatResponse:

>>> response = pc.assistants.chat_completions(
...     assistant_name="acme-support-bot",
...     messages=[{"content": "Which regions support BYOC?"}],
... )
>>> response.choices[0].message.content
'BYOC is available in aws us-east-1.'
>>> response.choices[0].finish_reason
'stop'
>>> hasattr(response, "citations")
False

See also

  • ChatResponse — the Pinecone-native shape, whose citations are objects you can render as source links.

  • ChatCompletionStream — the same answer delivered as chunks, from chat_completions(..., stream=True).

id: str
model: str
usage: ChatUsage
choices: list[ChatCompletionChoice]
class pinecone.models.assistant.chat.ChatCompletionChoice(*, index, message, finish_reason)[source]

Bases: StructDictMixin, Struct

A single answer in a chat completion response.

Reached as response.choices[0].

Variables:
  • index (int) – Position of this choice in the response’s choices list.

  • message (pinecone.models.assistant.chat.ChatCompletionMessage) – The ChatCompletionMessage for this choice; the text is at message.content.

  • finish_reason (str) – Why generation stopped: "stop" (the model finished), "length" (the token limit was reached), "content_filter" (content filtering rules blocked the output), or "tool_calls" (a tool call was triggered). The literal string "null" also reaches callers, so treat this as an open set of strings rather than switching exhaustively on the four above.

Parameters:
index: int
message: ChatCompletionMessage
finish_reason: str
class pinecone.models.assistant.chat.ChatCompletionMessage(*, role=None, content=None)[source]

Bases: StructDictMixin, Struct

The answer message inside a chat completion choice.

Reached as response.choices[0].message. Both fields are optional, so guard on content before using it.

Variables:
  • role (str | None) – The role of the message author, or None when the API did not report one.

  • content (str | None) – The answer text, or None when the choice carries none.

Parameters:
  • role (str | None)

  • content (str | None)

role: str | None
content: str | None

Assistant Context Models

class pinecone.models.assistant.context.ContextResponse(*, snippets, usage, id=None)[source]

Bases: StructDictMixin, Struct

The retrieved snippets for a query, with no answer generated over them.

Returned by context(). This is Pinecone’s retrieval step on its own: the snippets are source material for a prompt you assemble yourself, not prose to show a user. Reach for it when you want to run your own model over the assistant’s retrieval, or to see what an assistant would have been given.

snippets holds ContextSnippet, which is two classes. A TextSnippet has a string content. A MultimodalSnippet has a list of blocks instead — each a ContextTextBlock (block.text) or a ContextImageBlock (block.caption, plus block.image_data when the request set include_binary_content=True). Branch with isinstance, not on a type attribute: the snippet and block classes do not re-expose their wire tag, so snippet.type raises AttributeError. Both snippet classes carry score and snippet.reference.file.name.

Variables:
Parameters:

Examples

What comes back is retrieved source text, scored and attributed — no model was asked to write anything, which is why the completion token count is zero:

>>> from pinecone.models.assistant import TextSnippet
>>> response = pc.assistants.context(
...     assistant_name="acme-support-bot",
...     query="Which regions support BYOC?",
... )
>>> snippet = response.snippets[0]
>>> isinstance(snippet, TextSnippet)
True
>>> snippet.score
0.87
>>> snippet.content
'BYOC is available in aws us-east-1.'
>>> snippet.reference.file.name
'q3-revenue-review.pdf'
>>> response.usage.completion_tokens
0

Reading snippet.type to decide which variant you have does not work, even though the wire payload carries that tag:

>>> snippet.type
Traceback (most recent call last):
    ...
AttributeError: 'TextSnippet' object has no attribute 'type'

See also

  • ChatResponse — the generated answer over the same retrieval, from chat(), with citations you can render.

  • ContextOptions — the bundle that tunes retrieval for a chat request.

snippets: list[TextSnippet | MultimodalSnippet]
usage: ChatUsage
id: str | None
class pinecone.models.assistant.options.ContextOptions(*, top_k=None, snippet_size=None, multimodal=None, include_binary_content=None)[source]

Bases: StructDictMixin, Struct

Options controlling how context is retrieved for assistant operations.

All fields are optional and default to None, letting the server apply its own defaults.

Variables:
  • top_k (int | None) – Maximum number of context snippets to retrieve. The backend accepts 1-64; 0 and values above 64 are each rejected with a 400 (the spec documents a default of 16).

  • snippet_size (int | None) – Target size (in tokens) for each context snippet. The backend accepts 512-8192; anything outside that range is rejected with a 400 (the spec documents a default of 2048).

  • multimodal (bool | None) – Whether to include multimodal (image) content in retrieved context.

  • include_binary_content (bool | None) – Whether to include binary file content in retrieved context.

Parameters:
  • top_k (int | None)

  • snippet_size (int | None)

  • multimodal (bool | None)

  • include_binary_content (bool | None)

top_k: int | None
snippet_size: int | None
multimodal: bool | None
include_binary_content: bool | None
classmethod from_dict(d)[source]

Construct a ContextOptions from a plain dict representation.

Parameters:

d (dict[str, Any])

Return type:

ContextOptions

pinecone.models.assistant.context.ContextSnippet: TypeAlias = pinecone.models.assistant.context.TextSnippet | pinecone.models.assistant.context.MultimodalSnippet

One retrieved snippet, dispatched from the wire on a type tag.

Both variants carry score and reference; they differ in content. On a TextSnippet it is a string; on a MultimodalSnippet it is a list of blocks, so string handling of one will fail on the other.

Branch with isinstance: unlike the streaming chunks, these classes do not re-expose the wire tag, so snippet.type raises AttributeError.

class pinecone.models.assistant.context.TextSnippet(*, content, score, reference)[source]

Bases: StructDictMixin, Struct

A retrieved passage of plain text, from the wire tag "text".

The ContextSnippet variant whose content is a single string. A request with multimodal=True can instead yield a MultimodalSnippet, whose content is a list of blocks, so branch with isinstance before reading content.

Branching on the tag instead gives you AttributeError: 'TextSnippet' object has no attribute 'type'. That does not mean the payload lacked a type: the tag selected this class during decoding and was then dropped, so there is no attribute to read. The streaming chunk classes do keep theirs, which is why code moved over from a chat stream hits this.

Variables:
Parameters:
content: str
score: float
reference: FileReference
class pinecone.models.assistant.context.MultimodalSnippet(*, content, score, reference)[source]

Bases: StructDictMixin, Struct

A retrieved passage of mixed text and images, wire tag "multimodal".

The ContextSnippet variant whose content is a list of blocks rather than a string, so iterate it and branch with isinstance on ContextTextBlock versus ContextImageBlock.

Branching on the tag instead gives you AttributeError: 'MultimodalSnippet' object has no attribute 'type', and the same for either block class. That does not mean the payload lacked a type: the tag selected the class during decoding and was then dropped, so there is no attribute to read.

Variables:
Parameters:
content: list[ContextTextBlock | ContextImageBlock]
score: float
reference: FileReference
pinecone.models.assistant.context.ContextContentBlock: TypeAlias = pinecone.models.assistant.context.ContextTextBlock | pinecone.models.assistant.context.ContextImageBlock

One block of a MultimodalSnippet, text or image.

Branch with isinstance and read block.text on a ContextTextBlock or block.caption on a ContextImageBlock. These classes do not re-expose the wire tag, so block.type raises AttributeError.

class pinecone.models.assistant.context.ContextTextBlock(*, text)[source]

Bases: StructDictMixin, Struct

Text inside a MultimodalSnippet, wire tag "text".

Identify it with isinstance; block.type gives you AttributeError: 'ContextTextBlock' object has no attribute 'type', because the tag selected this class during decoding and was then dropped.

Variables:

text (str) – The text content of the block. Note the field is text here, not the content that TextSnippet uses.

Parameters:

text (str)

text: str
class pinecone.models.assistant.context.ContextImageBlock(*, caption, image_data=None)[source]

Bases: Struct

An image inside a MultimodalSnippet, wire tag "image".

The caption always arrives; the bytes do not. Ask for them with include_binary_content=True, and expect a much larger response.

Identify it with isinstance; block.type gives you AttributeError: 'ContextImageBlock' object has no attribute 'type', because the tag selected this class during decoding and was then dropped.

Variables:
Parameters:
caption: str
image_data: ContextImageData | None
class pinecone.models.assistant.context.ContextImageData(*, type, mime_type, data)[source]

Bases: StructDictMixin, Struct

The encoded bytes of an image in a multimodal context snippet.

Reached as block.image_data, and present only when the request set include_binary_content=True. data is text, not bytes — decode it before writing a file.

Variables:
  • type (str) – The encoding of data (e.g. "base64").

  • mime_type (str) – The MIME type of the image (e.g. "image/jpeg").

  • data (str) – The encoded image as a string, ready for a data URI or for base64.b64decode.

Parameters:
type: str
mime_type: str
data: str
pinecone.models.assistant.context.ContextReference

Alias for FileReference, the type of snippet.reference.

class pinecone.models.assistant.context.FileReference(*, file, pages=None, type=None)[source]

Bases: StructDictMixin, Struct

The source file a context snippet came from.

Reached as snippet.reference. Render reference.file.name as the label and reference.pages to point at the part of the document used.

Variables:
  • file (pinecone.models.assistant.file_model.AssistantFileModel) – The source file, as an AssistantFileModelfile.name for a label, file.id to fetch it again, and file.metadata for whatever you attached at upload.

  • pages (list[int] | None) – Page numbers relevant to the snippet, when the source is a paginated document such as a PDF. None for text, JSON, or Markdown sources.

  • type (str | None) – The kind of document referenced — "text", "json", "markdown", "pdf", or "doc_x" — or None when the payload omits it.

Parameters:
file: AssistantFileModel
pages: list[int] | None
type: str | None
pinecone.models.assistant.context.PageReference

Alias kept for backwards compatibility. Use FileReference instead.

Assistant Evaluation Models

class pinecone.models.assistant.evaluation.AlignmentResult(*, scores, facts, usage)[source]

Bases: StructDictMixin, Struct

How well a generated answer matched a ground-truth answer.

Returned by evaluate_alignment(). Read result.scores for the aggregate numbers and result.facts for the per-fact judgments that explain them — the scores tell you an answer is wrong, and the facts tell you where.

Variables:
Parameters:

Examples

The answer below contradicts the ground truth, so the scores come back low and facts records exactly where the disagreement is:

>>> result = pc.assistants.evaluate_alignment(
...     question="What is the capital of Spain?",
...     answer="Barcelona.",
...     ground_truth_answer="Madrid.",
... )
>>> result.scores
AlignmentScores(correctness=0.000, completeness=0.000, alignment=0.000)
>>> result.facts[0].entailment
'contradicted'
>>> result.facts[0].reasoning
'The answer names Barcelona instead of Madrid.'
>>> [f.fact for f in result.facts if f.entailment == "contradicted"]
['The capital of Spain is Madrid.']
>>> result.usage.total_tokens
38
scores: AlignmentScores
facts: list[EntailmentResult]
usage: ChatUsage
class pinecone.models.assistant.evaluation.AlignmentScores(*, correctness, completeness, alignment)[source]

Bases: StructDictMixin, Struct

The three aggregate scores of an alignment evaluation.

Reached as result.scores. Because alignment is a harmonic mean, a low score on either input drags it down, so read all three rather than tracking alignment alone.

Variables:
  • correctness (float) – Precision of the generated answer — how much of what it said holds up.

  • completeness (float) – Recall of the generated answer — how much of the ground truth it covered.

  • alignment (float) – Harmonic mean of correctness and completeness.

Parameters:
correctness: float
completeness: float
alignment: float
class pinecone.models.assistant.evaluation.EntailmentResult(*, fact, entailment, reasoning='')[source]

Bases: StructDictMixin, Struct

One evaluated fact, and how the answer stood against it.

Reached as an entry of result.facts. Filtering for "contradicted" gives you the specific places the answer and the ground truth disagree, which the aggregate scores cannot tell you.

Variables:
  • fact (str) – The fact under evaluation, as a sentence.

  • entailment (Literal['entailed', 'contradicted', 'neutral'] | str) – How the answer stood against the fact — "entailed", "contradicted", or "neutral". Typed as str rather than a closed set, so an unrecognized value decodes instead of raising.

  • reasoning (str) – Why the judgment was made. "" when the API returned none, so test for truthiness rather than for None.

Parameters:
  • fact (str)

  • entailment (Literal['entailed', 'contradicted', 'neutral'] | str)

  • reasoning (str)

fact: str
entailment: Literal['entailed', 'contradicted', 'neutral'] | str
reasoning: str

Assistant Streaming Models

class pinecone.models.assistant.streaming.ChatStream(stream)[source]

Bases: object

A Pinecone-native chat stream, returned by chat(..., stream=True).

Iterating it yields the ChatStreamChunk variants, which is the only way to reach citations and token usage. text() and collect() skip the dispatch and hand you text alone. The stream is single-pass: iterating, text(), and collect() all consume the same underlying iterator, so pick one.

Examples

from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")
stream = pc.assistants.chat(
    assistant_name="acme-support-bot",
    messages=[{"content": "What can you help me with?"}],
    stream=True,
)
for fragment in stream.text():
    print(fragment, end="", flush=True)

See also

Parameters:

stream (Iterator[ChatStreamChunk])

__init__(stream)[source]
Parameters:

stream (Iterator[StreamMessageStart | StreamContentChunk | StreamCitationChunk | StreamMessageEnd])

Return type:

None

text()[source]

Yield only the response text, dropping every non-content chunk.

Returns:

Iterator over delta.content of each StreamContentChunk, in arrival order. The start, citation and end chunks are discarded, so citations and token usage are not reachable through this method — iterate the stream itself for those.

Return type:

Iterator[str]

Examples

stream = pc.assistants.chat(
    assistant_name="acme-support-bot",
    messages=[{"content": "Explain vector databases in one sentence."}],
    stream=True,
)
for fragment in stream.text():
    print(fragment, end="", flush=True)

See also

collect() — the same fragments already joined into one string, for when you do not need to render as they arrive.

collect()[source]

Drain the whole stream and return the answer as one string.

Blocks until the server closes the stream, so nothing is rendered while the model is still generating.

Returns:

Every StreamContentChunk fragment joined in arrival order. Citations and token usage are discarded along with the other chunk types — iterate the stream itself for those.

Return type:

str

Examples

stream = pc.assistants.chat(
    assistant_name="acme-support-bot",
    messages=[{"content": "Explain vector databases in one sentence."}],
    stream=True,
)
print(stream.collect())

See also

text() — the fragments one at a time, for rendering the answer as it arrives.

pinecone.models.assistant.streaming.ChatStreamChunk

One chunk of a Pinecone-native chat stream, tagged by its type field.

Iterating a ChatStream yields these four classes, and branching on which one arrived is the whole contract. Each also exposes its tag as chunk.type, so a caller can dispatch on isinstance or on the string.

StreamMessageStart (type == "message_start")

Arrives once, first. No response text. model, role, and context_snippet_count — a 0 there means nothing relevant was retrieved, which you learn before the answer starts.

StreamContentChunk (type == "content_chunk")

Arrives many times, and is the only chunk carrying response text, at chunk.delta.content. Concatenate the fragments in arrival order.

StreamCitationChunk (type == "citation")

Arrives zero or more times, alongside the content chunks. chunk.citation.position is a character position in the response text, and each of chunk.citation.references has reference.file.name, reference.pages, and reference.highlight.

StreamMessageEnd (type == "message_end")

Arrives once, last. No response text. usage token counts and finish_reason.

Examples

from pinecone import (
    Pinecone,
    StreamCitationChunk,
    StreamContentChunk,
    StreamMessageEnd,
    StreamMessageStart,
)

pc = Pinecone(api_key="your-api-key")
stream = pc.assistants.chat(
    assistant_name="acme-support-bot",
    messages=[{"content": "Which regions support BYOC?"}],
    stream=True,
)

answer: list[str] = []
sources: list[str] = []
for chunk in stream:
    if isinstance(chunk, StreamMessageStart):
        if chunk.context_snippet_count == 0:
            print("no relevant context was retrieved")
    elif isinstance(chunk, StreamContentChunk):
        answer.append(chunk.delta.content)
        print(chunk.delta.content, end="", flush=True)
    elif isinstance(chunk, StreamCitationChunk):
        for reference in chunk.citation.references:
            sources.append(reference.file.name)
    elif isinstance(chunk, StreamMessageEnd):
        print(f"\nstopped because: {chunk.finish_reason}")

print("".join(answer), sources)

Use ChatStream.text() instead when you only want the text and no citations.

See also

ChatCompletionStreamChunk — the chunk type of the OpenAI-compatible stream, whose text is nested under choices and whose citations are woven into the text rather than delivered as objects.

class pinecone.models.assistant.streaming.ChatCompletionStream(stream)[source]

Bases: object

An OpenAI-compatible stream, from chat_completions(..., stream=True).

Iterating it yields ChatCompletionStreamChunk, whose text sits at chunk.choices[0].delta.content and can be None or "" on the role-only first chunk and the finish chunk; text() and collect() filter those out for you. Reach for this shape when you are pointing existing OpenAI client code at Pinecone. The stream is single-pass: iterating, text(), and collect() all consume the same underlying iterator, so pick one.

Examples

from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")
stream = pc.assistants.chat_completions(
    assistant_name="acme-support-bot",
    messages=[{"content": "What can you help me with?"}],
    stream=True,
)
for fragment in stream.text():
    print(fragment, end="", flush=True)

See also

  • ChatStream — the Pinecone-native shape, which delivers citations as objects you can render instead of weaving them into the text. Prefer it unless you need OpenAI compatibility.

  • AsyncChatCompletionStream — the AsyncPinecone equivalent.

Parameters:

stream (Iterator[ChatCompletionStreamChunk])

__init__(stream)[source]
Parameters:

stream (Iterator[ChatCompletionStreamChunk])

Return type:

None

text()[source]

Yield the response text, skipping role-only and finish chunks.

Returns:

Iterator over choices[0].delta.content of each chunk that has one, in arrival order. Chunks whose content is None or "", and chunks with an empty choices list, are skipped, as is usage on the final chunk — iterate the stream itself for that.

Return type:

Iterator[str]

Examples

stream = pc.assistants.chat_completions(
    assistant_name="acme-support-bot",
    messages=[{"content": "Explain vector databases in one sentence."}],
    stream=True,
)
for fragment in stream.text():
    print(fragment, end="", flush=True)

See also

collect() — the same fragments already joined into one string, for when you do not need to render as they arrive.

collect()[source]

Drain the whole stream and return the answer as one string.

Blocks until the server closes the stream, so nothing is rendered while the model is still generating.

Returns:

Every non-empty choices[0].delta.content fragment joined in arrival order. The final chunk’s usage is discarded — iterate the stream itself for that.

Return type:

str

Examples

stream = pc.assistants.chat_completions(
    assistant_name="acme-support-bot",
    messages=[{"content": "Explain vector databases in one sentence."}],
    stream=True,
)
print(stream.collect())

See also

text() — the fragments one at a time, for rendering the answer as it arrives.

class pinecone.models.assistant.streaming.ChatCompletionStreamChunk(*, id, choices, model=None, object=None, created=None, system_fingerprint=None, usage=None)[source]

Bases: StructDictMixin, Struct

One chunk of an OpenAI-compatible completion stream.

Unlike the Pinecone-native stream there is a single chunk type, so there is nothing to branch on: the text is at chunk.choices[0].delta.content and is None or "" on the role-only first chunk and the finish chunk. choices can also arrive empty, so guard on it before indexing.

Variables:
  • id (str) – Identifier of the completion, the same on every chunk of the stream.

  • choices (list[pinecone.models.assistant.streaming.ChatCompletionStreamChoice]) – The streaming choices, normally one. Read the text from choices[0].delta.content.

  • model (str | None) – Name of the model that generated the answer, or None if the server did not report it on this chunk.

  • object (str | None) – The object type (typically "chat.completion.chunk"), or None.

  • created (int | None) – Unix timestamp when the chunk was created, or None.

  • system_fingerprint (str | None) – Opaque fingerprint of the serving configuration, or None. Useful only for comparing two responses.

  • usage (pinecone.models.assistant.chat.ChatUsage | None) – ChatUsage token counts, populated on the final chunk and None on every earlier one.

Parameters:

See also

ChatStreamChunk — the Pinecone-native chunk types, which deliver citations as objects you can render.

id: str
choices: list[ChatCompletionStreamChoice]
model: str | None
object: str | None
created: int | None
system_fingerprint: str | None
usage: ChatUsage | None
class pinecone.models.assistant.streaming.ChatCompletionStreamChoice(*, index, delta, finish_reason=None)[source]

Bases: StructDictMixin, Struct

A single choice in a chat completion streaming chunk.

Reached as chunk.choices[0], and the wrapper for the fragment of text this chunk carries.

Variables:
  • index (int) – Position of this choice in the chunk’s choices list.

  • delta (pinecone.models.assistant.streaming.ChatCompletionStreamDelta) – The ChatCompletionStreamDelta for this choice; the text is at delta.content.

  • finish_reason (str | None) – None while generation is ongoing. Once set, why generation stopped: "stop" (the model finished), "length" (the token limit was reached), "content_filter" (content filtering rules blocked the output), or "tool_calls" (a tool call was triggered). The literal string "null" also reaches callers and is a different value from Python None, so treat this as an open set of strings rather than switching exhaustively on the four above.

Parameters:
index: int
delta: ChatCompletionStreamDelta
finish_reason: str | None
class pinecone.models.assistant.streaming.ChatCompletionStreamDelta(*, role=None, content=None)[source]

Bases: StructDictMixin, Struct

The delta payload within a chat completion streaming chunk.

Reached as chunk.choices[0].delta. Both fields are optional and both are commonly absent: the first chunk of a response typically carries role and no content, and the finish chunk carries neither.

Variables:
  • role (str | None) – The role of the message author, or None when the chunk does not restate it.

  • content (str | None) – The text fragment, or None when this chunk carries no text. Concatenate the non-empty fragments in arrival order to rebuild the answer.

Parameters:
  • role (str | None)

  • content (str | None)

role: str | None
content: str | None
class pinecone.models.assistant.streaming.StreamContentDelta(*, content)[source]

Bases: StructDictMixin, Struct

The delta payload within a content chunk.

Reached as chunk.delta on a StreamContentChunk. This is where the response text lives in a Pinecone-native chat stream.

Variables:

content (str) – The text fragment for this chunk. Concatenate the fragments in arrival order to rebuild the full answer.

Parameters:

content (str)

content: str
class pinecone.models.assistant.streaming.StreamMessageStart(*, model, role, id=None, context_snippet_count=None, content_filter_results=None)[source]

Bases: StructDictMixin, Struct

The chunk that opens a chat stream, carrying no response text.

Arrives once, before any content. Carries nothing you have to render, but context_snippet_count lets you detect “no relevant context found” before the answer starts arriving.

Variables:
  • type – Discriminator value "message_start".

  • model (str) – Name of the model that generated the answer, which need not be the name you requested.

  • role (str) – The role of the message author (e.g. "assistant").

  • id (str | None) – Identifier of the chat response, the same on every chunk of the stream, or None if the server did not report it here.

  • context_snippet_count (int | None) – Number of retrieved context snippets that were provided to the model, or None if the server did not report it. 0 means no relevant context was found for the query.

  • content_filter_results (dict[str, Any] | None) – Safety classifications reported by the LLM provider, or None when the provider returned none. Read spec for the provider’s name and results for a payload whose shape that provider defines.

Parameters:
  • model (str)

  • role (str)

  • id (str | None)

  • context_snippet_count (int | None)

  • content_filter_results (dict[str, Any] | None)

See also

ChatStreamChunk — the four chunk types and the loop that consumes them.

model: str
role: str
id: str | None
context_snippet_count: int | None
content_filter_results: dict[str, Any] | None
property type: str

Discriminator value, always "message_start".

class pinecone.models.assistant.streaming.StreamMessageEnd(*, id, usage=None, model=None, finish_reason=None, content_filter_results=None)[source]

Bases: StructDictMixin, Struct

The chunk that closes a chat stream, carrying usage and finish reason.

Arrives once, last, and carries no response text. Read finish_reason here to tell a complete answer from one the model cut short.

Variables:
  • type – Discriminator value "message_end".

  • id (str) – Identifier of the chat response, the same on every chunk of the stream.

  • usage (pinecone.models.assistant.chat.ChatUsage | None) – ChatUsage token counts for the whole request, or None if the server did not report them.

  • model (str | None) – Name of the model that generated the answer, or None if the server did not repeat it on this chunk.

  • finish_reason (str | None) – Why generation stopped: "stop" (the model finished), "length" (the token limit was reached), "content_filter" (content filtering rules blocked the output), or "tool_calls" (a tool call was triggered). The literal string "null" also reaches callers and is a different value from Python None, so treat this as an open set of strings rather than switching exhaustively on the four above.

  • content_filter_results (dict[str, Any] | None) – Safety classifications reported by the LLM provider, or None when the provider returned none. Read spec for the provider’s name and results for a payload whose shape that provider defines.

Parameters:

See also

ChatStreamChunk — the four chunk types and the loop that consumes them.

id: str
usage: ChatUsage | None
model: str | None
finish_reason: str | None
content_filter_results: dict[str, Any] | None
property type: str

Discriminator value, always "message_end".

class pinecone.models.assistant.streaming.StreamContentChunk(*, id, delta, model=None, content_filter_results=None)[source]

Bases: StructDictMixin, Struct

The only chunk type that carries response text, at delta.content.

Arrives many times per response, each with one fragment of the answer. A caller that renders the answer as it streams needs this chunk and nothing else.

Variables:
  • type – Discriminator value "content_chunk".

  • id (str) – Identifier of the chat response, the same on every chunk of the stream.

  • delta (pinecone.models.assistant.streaming.StreamContentDelta) – The StreamContentDelta holding this fragment; the text is at delta.content.

  • model (str | None) – Name of the model that generated the answer, or None if the server did not repeat it on this chunk.

  • content_filter_results (dict[str, Any] | None) – Safety classifications reported by the LLM provider for this fragment, or None when the provider returned none. Read spec for the provider’s name and results for a payload whose shape that provider defines.

Parameters:

See also

ChatStreamChunk — the four chunk types and the loop that consumes them.

id: str
delta: StreamContentDelta
model: str | None
content_filter_results: dict[str, Any] | None
property type: str

Discriminator value, always "content_chunk".

class pinecone.models.assistant.streaming.StreamCitationChunk(*, id, citation, model=None)[source]

Bases: StructDictMixin, Struct

The chunk that links a position in the answer to its source documents.

Arrives zero or more times, alongside the content chunks. This is the chunk a RAG caller needs to render sources: chunk.citation.position is the character position in the response text the citation annotates, and each entry of chunk.citation.references exposes reference.file (an AssistantFileModel, so reference.file.name and reference.file.metadata), reference.pages, and reference.highlight. The highlight is None unless the chat request set include_highlights=True.

Variables:
  • type – Discriminator value "citation".

  • id (str) – Identifier of the chat response, the same on every chunk of the stream.

  • citation (pinecone.models.assistant.chat.ChatCitation) – The ChatCitation holding position and references.

  • model (str | None) – Name of the model that generated the answer, or None if the server did not repeat it on this chunk.

Parameters:

See also

ChatStreamChunk — the four chunk types and the loop that consumes them.

id: str
citation: ChatCitation
model: str | None
property type: str

Discriminator value, always "citation".

class pinecone.models.assistant.streaming.AsyncChatStream(stream)[source]

Bases: object

A Pinecone-native chat stream from AsyncPinecone.

Iterating it yields the same ChatStreamChunk variants as ChatStream, so the branching contract is identical; only the async for/await mechanics differ. The stream is single-pass: iterating, text(), and collect() all consume the same underlying async iterator, so pick one.

Examples

import asyncio

from pinecone import AsyncPinecone

async def main() -> None:
    async with AsyncPinecone(api_key="your-api-key") as pc:
        stream = await pc.assistants.chat(
            assistant_name="acme-support-bot",
            messages=[{"content": "What can you help me with?"}],
            stream=True,
        )
        async for fragment in stream.text():
            print(fragment, end="", flush=True)

asyncio.run(main())

See also

Parameters:

stream (AsyncIterator[ChatStreamChunk])

__init__(stream)[source]
Parameters:

stream (AsyncIterator[StreamMessageStart | StreamContentChunk | StreamCitationChunk | StreamMessageEnd])

Return type:

None

async text()[source]

Yield only the response text, dropping every non-content chunk.

Returns:

Async iterator over delta.content of each StreamContentChunk, in arrival order. The start, citation and end chunks are discarded, so citations and token usage are not reachable through this method — iterate the stream itself for those.

Return type:

AsyncIterator[str]

Examples

async def main() -> None:
    stream = await pc.assistants.chat(
        assistant_name="acme-support-bot",
        messages=[{"content": "Explain vector databases in one sentence."}],
        stream=True,
    )
    async for fragment in stream.text():
        print(fragment, end="", flush=True)

See also

collect() — the same fragments already joined into one string, for when you do not need to render as they arrive.

async collect()[source]

Drain the whole stream and return the answer as one string.

Awaits until the server closes the stream, so nothing is rendered while the model is still generating.

Returns:

Every StreamContentChunk fragment joined in arrival order. Citations and token usage are discarded along with the other chunk types — iterate the stream itself for those.

Return type:

str

Examples

async def main() -> None:
    stream = await pc.assistants.chat(
        assistant_name="acme-support-bot",
        messages=[{"content": "Explain vector databases in one sentence."}],
        stream=True,
    )
    print(await stream.collect())

See also

text() — the fragments one at a time, for rendering the answer as it arrives.

class pinecone.models.assistant.streaming.AsyncChatCompletionStream(stream)[source]

Bases: object

An OpenAI-compatible stream from AsyncPinecone.

Iterating it yields the same ChatCompletionStreamChunk objects as ChatCompletionStream, with text at chunk.choices[0].delta.content; only the async for/await mechanics differ. The stream is single-pass: iterating, text(), and collect() all consume the same underlying async iterator, so pick one.

Examples

import asyncio

from pinecone import AsyncPinecone

async def main() -> None:
    async with AsyncPinecone(api_key="your-api-key") as pc:
        stream = await pc.assistants.chat_completions(
            assistant_name="acme-support-bot",
            messages=[{"content": "What can you help me with?"}],
            stream=True,
        )
        async for fragment in stream.text():
            print(fragment, end="", flush=True)

asyncio.run(main())

See also

AsyncChatStream — the Pinecone-native shape, which delivers citations as objects you can render instead of weaving them into the text. Prefer it unless you need OpenAI compatibility.

Parameters:

stream (AsyncIterator[ChatCompletionStreamChunk])

__init__(stream)[source]
Parameters:

stream (AsyncIterator[ChatCompletionStreamChunk])

Return type:

None

async text()[source]

Yield the response text, skipping role-only and finish chunks.

Returns:

Async iterator over choices[0].delta.content of each chunk that has one, in arrival order. Chunks whose content is None or "", and chunks with an empty choices list, are skipped, as is usage on the final chunk — iterate the stream itself for that.

Return type:

AsyncIterator[str]

Examples

async def main() -> None:
    stream = await pc.assistants.chat_completions(
        assistant_name="acme-support-bot",
        messages=[{"content": "Explain vector databases in one sentence."}],
        stream=True,
    )
    async for fragment in stream.text():
        print(fragment, end="", flush=True)

See also

collect() — the same fragments already joined into one string, for when you do not need to render as they arrive.

async collect()[source]

Drain the whole stream and return the answer as one string.

Awaits until the server closes the stream, so nothing is rendered while the model is still generating.

Returns:

Every non-empty choices[0].delta.content fragment joined in arrival order. The final chunk’s usage is discarded — iterate the stream itself for that.

Return type:

str

Examples

async def main() -> None:
    stream = await pc.assistants.chat_completions(
        assistant_name="acme-support-bot",
        messages=[{"content": "Explain vector databases in one sentence."}],
        stream=True,
    )
    print(await stream.collect())

See also

text() — the fragments one at a time, for rendering the answer as it arrives.

Filter Builder

Field builds metadata filter expressions with Python operators instead of nested dicts. Comparisons return a Condition, which combines with & and | and converts to the wire form with to_dict().

class pinecone.utils.filter_builder.Field(name)[source]

Bases: object

One metadata field, ready to be compared.

Reach it with from pinecone import Field. Naming a field produces no filter on its own; applying an operator to it returns a Condition, and Condition.to_dict() turns that into the filter value.

The two equality operators are Python’s own: Field("genre") == "drama" builds $eq and != builds $ne. Because == is overloaded to build a filter rather than answer a question, a Field never compares equal to anything and cannot be used as a dict key or set member.

The ordering operators — gt(), gte(), lt(), lte() — are numeric only. is_in() and not_in() take a list, exists() takes nothing.

Examples

>>> from pinecone import Field
>>> (Field("genre") == "drama").to_dict()
{'genre': {'$eq': 'drama'}}
>>> (Field("genre") != "documentary").to_dict()
{'genre': {'$ne': 'documentary'}}

See also

Condition — combining these with & and |.

Parameters:

name (str)

__init__(name)[source]
Parameters:

name (str)

Return type:

None

gt(value)[source]

$gt — the field is greater than value (numeric only).

Raises:

TypeError – If value is not an int or float. A bool is rejected as well, though Python counts it as an int; compare a boolean field with == instead.

Parameters:

value (int | float)

Return type:

Condition

Examples

>>> from pinecone import Field
>>> Field("rating").gt(4.5).to_dict()
{'rating': {'$gt': 4.5}}
gte(value)[source]

$gte — the field is greater than or equal to value (numeric only).

Raises:

TypeError – If value is not an int or float. A bool is rejected as well, though Python counts it as an int; compare a boolean field with == instead.

Parameters:

value (int | float)

Return type:

Condition

Examples

>>> from pinecone import Field
>>> Field("year").gte(2020).to_dict()
{'year': {'$gte': 2020}}
lt(value)[source]

$lt — the field is less than value (numeric only).

Raises:

TypeError – If value is not an int or float. A bool is rejected as well, though Python counts it as an int; compare a boolean field with == instead.

Parameters:

value (int | float)

Return type:

Condition

Examples

>>> from pinecone import Field
>>> Field("price_usd").lt(25).to_dict()
{'price_usd': {'$lt': 25}}
lte(value)[source]

$lte — the field is less than or equal to value (numeric only).

Raises:

TypeError – If value is not an int or float. A bool is rejected as well, though Python counts it as an int; compare a boolean field with == instead.

Parameters:

value (int | float)

Return type:

Condition

Examples

>>> from pinecone import Field
>>> Field("duration_minutes").lte(120).to_dict()
{'duration_minutes': {'$lte': 120}}
__eq__(value)[source]

$eq — equal to.

Parameters:

value (object)

Return type:

Condition

__ne__(value)[source]

$ne — not equal to.

Parameters:

value (object)

Return type:

Condition

is_in(values)[source]

$in — the field’s value is one of values.

Examples

>>> from pinecone import Field
>>> Field("genre").is_in(["drama", "thriller"]).to_dict()
{'genre': {'$in': ['drama', 'thriller']}}
Parameters:

values (list[str | int | float | bool])

Return type:

Condition

not_in(values)[source]

$nin — the field’s value is none of values.

Examples

>>> from pinecone import Field
>>> Field("genre").not_in(["horror"]).to_dict()
{'genre': {'$nin': ['horror']}}
Parameters:

values (list[str | int | float | bool])

Return type:

Condition

exists()[source]

$exists — the field is present on the record, whatever its value.

Examples

>>> from pinecone import Field
>>> Field("release_year").exists().to_dict()
{'release_year': {'$exists': True}}
Return type:

Condition

class pinecone.utils.filter_builder.Condition(filter_dict)[source]

Bases: object

One filter clause, or several combined.

Returned by every Field operator; you never construct one directly. Combine conditions with & for $and and | for $or, then call to_dict() to get the value to pass as filter.

Combining flattens same-operator nesting, so chaining three & gives one $and of three clauses rather than nested pairs. Mixing the two operators nests as Python’s precedence dictates, which is why the operands want parentheses.

Examples

>>> from pinecone import Field
>>> ((Field("genre") == "drama") & Field("year").gte(2020)).to_dict()
{'$and': [{'genre': {'$eq': 'drama'}}, {'year': {'$gte': 2020}}]}
Parameters:

filter_dict (dict[str, Any])

__init__(filter_dict)[source]
Parameters:

filter_dict (dict[str, Any])

Return type:

None

__and__(other)[source]
Parameters:

other (Condition)

Return type:

Condition

__or__(other)[source]

Return self|value.

Parameters:

other (Condition)

Return type:

Condition

to_dict()[source]

Return the condition as the dict to pass as filter.

The dict is the builder’s own state, not a copy, so mutating the result mutates the condition.

Returns:

The filter, e.g. {"year": {"$gte": 2020}}.

Raises:

ValueError – If the condition is empty — reachable only by constructing Condition directly with {}, which no Field operator does.

Return type:

dict[str, Any]

Examples

>>> from pinecone import Field
>>> Field("year").gte(2020).to_dict()
{'year': {'$gte': 2020}}