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:
StructEverything the control plane knows about one index.
What
describe,createandconfigurereturn, and what iteratinglistyields. Two fields carry most of the traffic:status.readyis what you poll to know the index can serve requests, andhostis what you hand toPinecone.index()to get a data-plane client. Everything about the index’s shape — dimension, metric, which fields are searchable — is inschema.- Variables:
name (str) – The name of the index.
host (str | None) – Where the index is served. Pass it to
Pinecone.index()to open a data-plane client.Nonewhile the index is still initializing and has not been assigned one.private_host (str | None) – The private-endpoint hostname for this index when the project has Private Endpoints configured, or
Noneotherwise. Clients inside a VPC should connect to this host instead ofhost.status (pinecone.models.indexes.index.IndexStatus) – An
IndexStatus;status.readyis the field to poll.schema (pinecone.models.indexes.schema.IndexSchema) – An
IndexSchemanaming every field in the index and what each can do — where dimension, metric and vector type live.deployment (pinecone.models.indexes.deployment.ManagedDeployment | pinecone.models.indexes.deployment.PodDeployment | pinecone.models.indexes.deployment.ByocDeployment) – Deployment configuration — a
ManagedDeployment,PodDeployment, orByocDeployment, discriminated ondeployment_type.deletion_protection (str) – Whether deletion protection is enabled (
"enabled"or"disabled").read_capacity (pinecone.models.indexes.read_capacity.ReadCapacityOnDemandResponse | pinecone.models.indexes.read_capacity.ReadCapacityDedicatedResponse | None) – Read capacity configuration and status, or
Noneif the server response omits it.tags (dict[str, str] | None) – User-defined key-value tags attached to the index, or
Noneif no tags are set (the API returns"tags": nullrather than{}).source_collection (str | None) – Name of the collection this index was created from, or
None.source_backup_id (str | None) – ID of the backup this index was restored from, or
None.cmek_id (str | None) – ID of the customer-managed encryption key protecting this index, or
Noneif CMEK is not configured.
- Parameters:
name (str)
status (IndexStatus)
schema (IndexSchema)
deployment (ManagedDeployment | PodDeployment | ByocDeployment)
deletion_protection (str)
host (str | None)
read_capacity (ReadCapacityOnDemandResponse | ReadCapacityDedicatedResponse | None)
private_host (str | None)
source_collection (str | None)
source_backup_id (str | None)
cmek_id (str | None)
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)
IndexModelalso reads like a mapping:index["host"]and"host" in indexwork for every attribute above, andto_dict()returns the same key set.Changed in version 10.0:
dimension,metric,vector_type,spec,embedandcreated_atare no longer plain attributes.The first five survive as deprecated properties computed from the fields above:
dimension,metricandvector_typeresolve when the schema has exactly one vector field,specrebuilds the 9.xIndexSpecfromdeployment,read_capacityandschema, andembedrebuilds the 9.xModelIndexEmbedfrom the schema’s semantic text field. Every spelling agrees:index.metric,index["metric"],"metric" in indexand the"metric"key ofto_dict()all answer from the same lookup. Where an accessor is ambiguous — two dense fields, say — the attribute raisesAttributeError, the item access raisesKeyErrorcarrying that same explanation,inisFalse, andto_dict()omits the key.created_atis genuinely gone, because the 2026-07 API does not return a creation timestamp. Reading it raisesAttributeError, andindex["created_at"]aKeyError, saying so.- status: IndexStatus¶
- schema: IndexSchema¶
- deployment: ManagedDeployment | PodDeployment | ByocDeployment¶
- read_capacity: ReadCapacityOnDemandResponse | ReadCapacityDedicatedResponse | None¶
- property dimension: int | None¶
Width of the schema’s sole dense vector field.
Nonefor a sparse-only schema, since sparse vectors have no fixed dimension. RaisesAttributeErrorwhen 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 into_dict()— all three resolve exactly when this property does.Deprecated since version 10.0: Read
index.schema.fields["<field-name>"].dimensioninstead.
- 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. RaisesAttributeErrorwhen more than one field could answer.Also readable as
index["metric"], testable with"metric" in index, and present into_dict()— all three resolve exactly when this property does.Deprecated since version 10.0: Read
index.schema.fields["<field-name>"].metricinstead.
- property vector_type: str¶
"dense"or"sparse", for a schema with one vector field.Raises
AttributeErrorwhen 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 into_dict()— all three resolve exactly when this property does.Deprecated since version 10.0: Inspect the field types in
index.schema.fieldsinstead.
- property spec: IndexSpec¶
The index’s placement, in the 9.x
specshape.An
IndexSpecwith exactly one ofserverless,podandbyocset, chosen bydeployment.deployment_type, so 9.x reads likeindex.spec.serverless.regionandindex.spec.pod.pod_typekeep working. Every value is copied out ofdeployment,read_capacity,schemaandsource_collection— nothing here is fetched, and the object is rebuilt on each access rather than cached.pod.metadata_configis alwaysNone: metadata is indexed automatically at upsert, so 2026-07 has no such configuration to report.pod.podsis computed asreplicas * shards, the same identity the create path enforces when translating a 9.xpods=.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
deploymentwithisinstance()instead —ManagedDeployment,PodDeploymentandByocDeploymentcarry the same values with one less level of nesting, and read capacity is top-level atread_capacity.
- property embed: ModelIndexEmbed | None¶
Integrated-embedding configuration, in the 9.x
embedshape.A
ModelIndexEmbedbuilt from the schema’s soleSemanticTextField, so 9.x reads likeindex.embed.modelandindex.embed.field_mapkeep working.Nonefor an index with no semantic text field, which is what 9.x reported for a non-integrated index.dimensionandvector_typeare alwaysNone: a 2026-07semantic_textfield reports neither, and inventing them would mean guessing. RaisesAttributeErrorwhen the schema has more than one semantic text field, naming them — as withmetric, 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
SemanticTextFieldout ofindex.schema.fieldsinstead.
- to_dict()[source]¶
Return the whole model as nested plain dicts, for logging or JSON.
status,schema,deploymentandread_capacitybecome dicts too, each keeping the key that identifies which variant it is (deployment_type,mode,type). ALegacyMetadataFieldis emitted without atype, matching the wire format. Optional fields that areNoneare present with aNonevalue rather than omitted, so the key set is the same for every index.The deprecated
dimension,metric,vector_type,specandembedkeys are included whenever the like-named property resolves, which is the key set 9.x emitted.specandembedare nested dicts, sod["spec"]["serverless"]["region"]reads as it did in 9.x. An index whose schema makes a key ambiguous omits it rather than guessing, andcreated_atis 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.
- class pinecone.models.indexes.list.IndexList(indexes)[source]¶
Bases:
objectThe indexes that the legacy
pc.list_indexes()hands back.A thin sequence of
IndexModel: iterate it, subscript it, take itslen(), or callnames(). Not constructed directly.New code should call
pc.indexes.list(), which returns aPaginatorinstead — 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
listto 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 ofIndexModel.to_dict.- Return type:
Examples
>>> list(pc.list_indexes().to_dict()) ['data']
- class pinecone.models.indexes.index.IndexStatus(*, ready, state)[source]¶
Bases:
StructDictMixin,StructWhether an index can serve requests yet, and what it is busy doing.
Branch on
ready; readstatewhen 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
createwaits on for you unless you passedtimeout=-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 reportreadywhile a scaling state is in progress, so the two answer different questions.
- Parameters:
- class pinecone.models.indexes.index.IndexTags[source]¶
Bases:
dictAn index’s tags: an ordinary dict, plus
to_dict()for symmetry.IndexModelwraps whatever tags come back in this so that every nested model on the response answersto_dict().
- class pinecone.models.indexes.specs.ServerlessSpec(*, cloud, region, read_capacity=None, schema=None)[source]¶
Bases:
StructDictMixin,StructA serverless index, described the 9.x way.
Deprecated sugar for
create()’sspec=: the SDK turns it into a manageddeployment=, lifting anyread_capacityout to the top level as it goes.spec=anddeployment=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
Nonefor 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 withPineconeValueErrorsayingschema is required— which reads as though you passed none. Passschema=tocreate()directly.
- Parameters:
Deprecated since version 10.0: Pass
deployment={"deployment_type": "managed", "cloud": ..., "region": ...}instead.
- 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,StructA pod-based index, described the 9.x way.
Deprecated sugar for
create()’sspec=, translated into a poddeployment=.spec=anddeployment=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 raisesPineconeValueError, because there is no independent pod count to translate it into.metadata_config (dict[str, Any] | None) – Rejected with
PineconeTypeErrorwhen set — metadata fields are indexed automatically at upsert, so there is nothing to declare at create time.source_collection (str | None) – Rejected with
PineconeTypeErrorwhen set. UsePinecone.create_index_from_backupto restore a backup instead.
- Parameters:
Deprecated since version 10.0: Pass
deployment={"deployment_type": "pod", "environment": ..., "pod_type": ..., "replicas": ..., "shards": ...}instead.
- class pinecone.models.indexes.specs.ByocSpec(*, environment, read_capacity=None, schema=None)[source]¶
Bases:
StructDictMixin,StructA BYOC index, described the 9.x way.
Deprecated sugar for
create()’sspec=, translated into a BYOCdeployment=with anyread_capacitylifted to the top level.spec=anddeployment=are mutually exclusive.- Variables:
- Parameters:
Deprecated since version 10.0: Pass
deployment={"deployment_type": "byoc", "environment": ...}instead.
- class pinecone.models.indexes.specs.IntegratedSpec(*, cloud, region, embed)[source]¶
Bases:
StructDictMixin,StructCloud, region and embedding config bundled into one 9.x-style spec.
Unlike its sibling specs this one has no
deployment=translation, so passing it asspec=tocreate()raisesPineconeTypeErrorrather than being rewritten. Callcreate_for_model()withcloud,regionandembedinstead — the same three values, as arguments.- Variables:
cloud (str) – Public cloud to run in, e.g.
"aws".region (str) – Region within that cloud, e.g.
"us-east-1".embed (pinecone.models.indexes.specs.EmbedConfig) – An
EmbedConfig.
- Parameters:
cloud (str)
region (str)
embed (EmbedConfig)
Deprecated since version 10.0: Pass
cloud=,region=andembed=tocreate_for_model().- embed: EmbedConfig¶
- class pinecone.models.indexes.specs.EmbedConfig(*, model, field_map, dimension=None, metric=None, read_parameters=None, write_parameters=None)[source]¶
Bases:
StructWhich model embeds your text, and which field it reads.
One of the shapes
create_for_model()accepts forembed=— a plain dict with the same keys works too. The field it names comes back on the created index as aSemanticTextField, and the model cannot be changed afterwards.- Variables:
model (str) – Embedding model to use, e.g.
"multilingual-e5-large". SeeEmbedModel.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.
Nonetakes the model’s own dimension. Note thatto_dict()omits this field;create_for_modelreads the attribute directly, so the create path is unaffected, but a dict you build withto_dict()loses it.metric (str | None) – How similarity is scored, or
Nonefor 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:
- to_dict()[source]¶
Serialize to a plain dict of
model,field_mapand metric.read_parametersandwrite_parameterscome out as empty dicts rather than being omitted when they were never set, anddimensionis left out entirely — pass theEmbedConfigitself tocreate_for_model, which reads the attribute, rather than the output of this method.
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,StructA 9.x-shaped view of where an index runs.
What
IndexModel.specreturns. Exactly one ofserverless,podandbyocis set, chosen by thedeployment_typeof the index’sdeployment.- Variables:
serverless (pinecone.models.indexes.index.ServerlessSpecInfo | None) – A
ServerlessSpecInfofor a"managed"deployment, elseNone.pod (pinecone.models.indexes.index.PodSpecInfo | None) – A
PodSpecInfofor a"pod"deployment, elseNone.byoc (pinecone.models.indexes.index.ByocSpecInfo | None) – A
ByocSpecInfofor a"byoc"deployment, elseNone.
- Parameters:
serverless (ServerlessSpecInfo | None)
pod (PodSpecInfo | None)
byoc (ByocSpecInfo | None)
Deprecated since version 10.0: Branch on
index.deploymentwithisinstance()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,StructThe serverless half of a 9.x
index.spec.Built on demand by
IndexModel.specfrom aManagedDeploymentplus the index’s top-levelread_capacityandschema. 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_capacityas a plain dict with its"mode"key, orNonewhen the response omits it. 2026-07 carries this at the top level; readIndexModel.read_capacityfor the typed object.source_collection (str | None) – The index’s top-level
source_collection.schema (dict[str, Any] | None) – The index’s typed
schemaas a plain dict. Note the shift: in 9.x this key held the metadata-indexing schema and wasNoneby default, whereas the 2026-07 schema declares every field including the vector ones.
- Parameters:
Deprecated since version 10.0: Read
index.deployment,index.read_capacityandindex.schemadirectly.
- class pinecone.models.indexes.index.PodSpecInfo(*, environment, pod_type, replicas=None, shards=None, pods=None, metadata_config=None, source_collection=None)[source]¶
Bases:
StructDictMixin,StructThe pod half of a 9.x
index.spec.Built on demand by
IndexModel.specfrom aPodDeployment.- 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.xpods=.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:
Deprecated since version 10.0: Read
index.deploymentdirectly.
- class pinecone.models.indexes.index.ByocSpecInfo(*, environment, read_capacity=None, schema=None)[source]¶
Bases:
StructDictMixin,StructThe BYOC half of a 9.x
index.spec.Built on demand by
IndexModel.specfrom aByocDeploymentplus the index’s top-levelread_capacityandschema.- Variables:
environment (str) – BYOC environment, from
deployment.environment.read_capacity (dict[str, Any] | None) – The index’s
read_capacityas a plain dict, orNonewhen the response omits it.schema (dict[str, Any] | None) – The index’s typed
schemaas a plain dict, with the same semantic shift noted onServerlessSpecInfo.
- Parameters:
Deprecated since version 10.0: Read
index.deployment,index.read_capacityandindex.schemadirectly.
- 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,StructA 9.x-shaped view of an index’s integrated-embedding configuration.
What
IndexModel.embedreturns, built from the singleSemanticTextFieldin 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, orNonewhen the field uses the model’s own default.dimension (int | None) – Always
None. A 2026-07semantic_textfield 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_modelnames the field after thefield_maptext 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
SemanticTextFieldout ofindex.schema.fieldsinstead.
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:
StructThe body
create()sends.Assembled from that method’s keyword arguments; the field descriptions there are the ones to read.
schemais the only required member.- Variables:
schema (dict[str, Any] | pinecone.models.indexes.schema.IndexSchema) – What the index will hold, as an
IndexSchemaor the equivalent dict. Only searchable fields are declared —dense_vector,sparse_vector, orstringwith afull_text_searchconfig.name (str | None) – Name for the index; the server assigns one when omitted.
deployment (dict[str, Any] | pinecone.models.indexes.deployment.ManagedDeployment | pinecone.models.indexes.deployment.PodDeployment | pinecone.models.indexes.deployment.ByocDeployment | None) – Where the index runs, discriminated on
deployment_type(managed,podorbyoc). Omitted means a managed index on AWSus-east-1.read_capacity (dict[str, Any] | None) – Read capacity for a managed or BYOC index.
deletion_protection (str | None) –
"enabled"or"disabled".tags (dict[str, str] | None) – Key-value tags to attach to the index.
source_collection (str | None) – Name of a collection to seed the index from.
source_backup_id (str | None) – ID of a backup to restore the index from.
cmek_id (str | None) – Customer-managed encryption key to encrypt the index with. Accepted for managed and BYOC indexes with no full-text search field.
- Raises:
PineconeValueError – If
deploymentnames adeployment_typeoutside 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)
deletion_protection (str | None)
source_collection (str | None)
source_backup_id (str | None)
cmek_id (str | None)
- schema: dict[str, Any] | IndexSchema¶
- deployment: dict[str, Any] | ManagedDeployment | PodDeployment | ByocDeployment | None¶
- class pinecone.models.indexes.requests.ConfigureIndexRequest(*, schema=None, deployment=None, read_capacity=None, deletion_protection=None, tags=None)[source]¶
Bases:
StructThe 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_textfield’s parameters can be changed; fields cannot be added or removed.deployment (dict[str, Any] | None) – Deployment changes, for pod-based indexes only —
replicasandpod_type, with nodeployment_typekey.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:
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:
StructEvery 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 fromIndexModel.schemaafterwards. 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
fieldsnames a field type through itstypekey, 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 withPineconeValueError, saying the schema “looks like a 9.x metadata schema” because none of its fields carry atype.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_vectorA fixed-width vector of floats, scored by a similarity metric. Carries
dimensionandmetric— seeDenseVectorField.sparse_vectorVariable-length index/value pairs for keyword-style scoring, with no dimension and no choice of metric — see
SparseVectorField.stringText made full-text searchable by a
full_text_searchconfig — seeStringField.
Read back but not declarable — sending one on create is rejected:
semantic_textText Pinecone embeds for you on write and on read.
create_for_model()is the only way to get one — seeSemanticTextField.float,boolean,string_listNumeric, boolean and tag-style metadata, indexed for filtering automatically at upsert time — see
FloatField,BooleanField,StringListField.integerNumeric metadata on indexes predating the normalisation of numbers to float — see
IntegerField.
A field from an index older than typed schemas arrives with no
typeat all and becomes aLegacyMetadataField.Note
create_for_model()also takes aschema=, 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 describescreate()’sschema=.- 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 theschema=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
typekey; aLegacyMetadataFieldis 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 tocreate.
- 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:
StructA 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
typein aschema=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 —SchemaBuilderrejects 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; seeMetricfor how to choose.description (str | None) – Free-text note about the field, or
Nonewhen none was given. Always present in responses.
- Parameters:
Examples
The
schema=entry that declares one:{"embedding": {"type": "dense_vector", "dimension": 1536, "metric": "cosine"}}
- class pinecone.models.indexes.schema.SparseVectorField(*, description=None)[source]¶
Bases:
StructVariable-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
typein aschema=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"}}
- class pinecone.models.indexes.schema.SemanticTextField(*, model, metric=None, description=None, read_parameters=None, write_parameters=None)[source]¶
Bases:
StructText 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 thefield_maptext entry. Writing"type": "semantic_text"into aschema=you pass tocreateis 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.xspec=IntegratedSpec(...)route is gone too; it raisesPineconeTypeErrornamingcreate_for_modelas 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
Nonewhen 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"}, orNone.write_parameters (dict[str, Any] | None) – Extra arguments passed to the model when embedding an upsert, e.g.
{"input_type": "passage"}, orNone.
- Parameters:
- class pinecone.models.indexes.schema.StringField(*, description=None, filterable=False, full_text_search=None)[source]¶
Bases:
StructText, either full-text searchable or filterable — never both.
A string field you declare on create must carry a
full_text_searchconfig, 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. Itstypein aschema=dict is"string".In responses, a searchable field reports its
full_text_searchobject and a filter-only field reports justfilterable.- 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. Sendingfilterable=Truealongsidefull_text_searchdoes 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;Nonemeans it is not.
- Parameters:
description (str | None)
filterable (bool)
full_text_search (FullTextSearchConfig | None)
Examples
The
schema=entry that declares one:{"title": {"type": "string", "full_text_search": {}}}
- full_text_search: FullTextSearchConfig | None¶
- class pinecone.models.indexes.schema.StringListField(*, description=None, filterable=False)[source]¶
Bases:
StructTag-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_listin aschema=on create is rejected, and one rejected field fails the whole schema. Upsert the list as an ordinary document value instead.- Variables:
- Parameters:
- class pinecone.models.indexes.schema.BooleanField(*, description=None, filterable=False)[source]¶
Bases:
StructBoolean metadata, filterable.
Response-only. You read one back for a field the server indexed for you at upsert time; sending
booleanin aschema=on create is rejected, and one rejected field fails the whole schema. Upsert the value as an ordinary document value instead.- Variables:
- Parameters:
- class pinecone.models.indexes.schema.IntegerField(*, description=None, filterable=False)[source]¶
Bases:
StructInteger metadata on an index that predates numeric normalisation.
Response-only, and the one field type with a sharp edge. Numbers are normalised to
floatat upsert time now, sointegeronly ever comes back from an older index. There is nointegertype 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.SchemaBuilderhas no method for this type and refuses{"type": "integer"}passed throughadd_custom_field(), so building the schema that way fails client-side with an explanation instead.- Variables:
- Parameters:
- class pinecone.models.indexes.schema.FloatField(*, description=None, filterable=False)[source]¶
Bases:
StructNumeric metadata, filterable and range-comparable.
Double-precision throughout, which is why range filters like
year >= 2020work on it and why there is no separate integer type: integers are stored and filtered as floats, andfloatis 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
floatin aschema=on create is rejected, and one rejected field fails the whole schema. Upsert the number as an ordinary document value instead.- Variables:
- Parameters:
- class pinecone.models.indexes.schema.LegacyMetadataField(*, filterable)[source]¶
Bases:
StructA metadata field from an index older than typed schemas.
These fields carry no
typeat all on the wire, and their original data type was never recorded, sofilterableis 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, butmsgspec.json.encodeof this class does emit it.
- class pinecone.models.indexes.schema.FullTextSearchConfig(*, language=None, stemming=None, stop_words=None, ngram=None)[source]¶
Bases:
StructHow a string field’s text is analysed for full-text search.
Its presence on a
StringFieldis what makes the field full-text searchable at all;Nonemeans it is not. Every key is optional, so an emptyFullTextSearchConfig()is a valid way to say “searchable, server defaults please”. Responses always reportlanguage,stemmingandstop_wordsas 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.Nonetakes the server default of English.stemming (bool | None) – Fold tokens to their root form, so
runningmatchesrun.Nonetakes the server default of off.stop_words (bool | None) – Drop common words like
thefrom the index. Requiresstemming=True, and is not supported for every language — the rejection names the unsupported language by its English name rather than the code you sent.Nonetakes the server default of off.ngram (pinecone.models.indexes.schema.NgramConfig | None) – A
NgramConfigto index character runs instead of words, orNonefor word tokenization. Mutually exclusive withstemmingandstop_words.
- Parameters:
language (str | None)
stemming (bool | None)
stop_words (bool | None)
ngram (NgramConfig | None)
- ngram: NgramConfig | None¶
- class pinecone.models.indexes.schema.NgramConfig(*, min_gram, max_gram, prefix_only=False)[source]¶
Bases:
StructTokenize a string field into character n-grams instead of words.
Word tokenization matches whole words, so a search for
headmissesheadphones. N-gram tokenization indexes runs of characters instead, which is what makes substring matching and autocomplete work. It cannot be combined withstemmingorstop_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 toFalse.
- Parameters:
Examples
Substring matching on a product title:
{"title": {"type": "string", "full_text_search": { "ngram": {"min_gram": 2, "max_gram": 3}}}}
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 anIndexModel.deploymentwithisinstancebefore reading fields only one variant has.
- class pinecone.models.indexes.deployment.ManagedDeployment(*, cloud, region, environment=None)[source]¶
Bases:
StructA 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_typeis"managed".- Variables:
cloud (str) – Public cloud to run in —
"aws","gcp", or"azure". SeeCloudProvider.region (str) – Region within that cloud, e.g.
"us-east-1".environment (str | None) – The internal cell hosting the index, derived from
cloudandregion. Response-only and informational; you cannot set it, and it is not something to build on.
- Parameters:
Examples
The
deployment=argument that asks for one:{"deployment_type": "managed", "cloud": "aws", "region": "us-east-1"}
- class pinecone.models.indexes.deployment.PodDeployment(*, environment, pod_type, replicas, shards)[source]¶
Bases:
StructA 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_typeis"pod". Every attribute below is required on create — leaving outreplicasorshardsis 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". SeePodIndexEnvironment.pod_type (str) – Hardware family and size, e.g.
"p1.x1". SeePodType.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
configurecan change later, along withpod_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:
- class pinecone.models.indexes.deployment.ByocDeployment(*, environment)[source]¶
Bases:
StructA 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_typeis"byoc".
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 anIndexModel.read_capacitywithisinstancebefore readingdedicated, which only one variant has.
- class pinecone.models.indexes.read_capacity.ReadCapacityOnDemandResponse(*, status)[source]¶
Bases:
StructRead 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
modeis"OnDemand". Reach forReadCapacityDedicatedResponsewhen 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:
StructRead capacity served by nodes provisioned for this index alone.
Its
modeis"Dedicated", and unlike on-demand it reports the hardware behind it, because you chose it. Changing the counts putsstatus.stateinto"Scaling"until the new shape is in place.- Variables:
dedicated (pinecone.models.indexes.read_capacity.ReadCapacityDedicatedConfig) – A
ReadCapacityDedicatedConfig— node type and shard/replica counts.status (pinecone.models.indexes.read_capacity.ReadCapacityStatus) – A
ReadCapacityStatus.
- Parameters:
dedicated (ReadCapacityDedicatedConfig)
status (ReadCapacityStatus)
- dedicated: ReadCapacityDedicatedConfig¶
- status: ReadCapacityStatus¶
- class pinecone.models.indexes.read_capacity.ReadCapacityDedicatedConfig(*, node_type, scaling, manual=None)[source]¶
Bases:
StructWhat the dedicated read tier is made of.
- Variables:
node_type (str) – Machine class the read tier runs on —
"b1", or"t1"for more processing power and memory per node.scaling (str) – How the shard and replica counts are decided, e.g.
"Manual".manual (pinecone.models.indexes.read_capacity.ScalingConfigManual | None) – The counts themselves, as a
ScalingConfigManual. Present whenscalingis"Manual".
- Parameters:
node_type (str)
scaling (str)
manual (ScalingConfigManual | None)
- manual: ScalingConfigManual | None¶
- class pinecone.models.indexes.read_capacity.ReadCapacityStatus(*, state, current_shards=None, current_replicas=None, error_message=None)[source]¶
Bases:
StructWhether 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 readerror_message.current_shards (int | None) – Current number of active shards.
Nonefor an index with on-demand read capacity, which has no fixed shard count.current_replicas (int | None) – Current number of active replicas.
Nonefor an index with on-demand read capacity, which has no fixed replica count.error_message (str | None) – Message describing a read-capacity configuration issue;
Noneunlessstateis"Error".
- Parameters:
- class pinecone.models.indexes.read_capacity.ScalingConfigManual(*, shards, replicas)[source]¶
Bases:
StructThe shard and replica counts you chose for dedicated read capacity.
Present when
scalingis"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.
0is 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:
Vector Models¶
- class pinecone.models.vectors.vector.Vector(id, values=<factory>, sparse_values=None, metadata=None)[source]¶
Bases:
DictLikeStruct,StructOne 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:
Dense —
values, a list of floats whose length equals thedimensionof the index field it is written to, ranked by that field’smetric. 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.Sparse —
sparse_values, which names only the non-zero dimensions as parallelindicesandvalueslists and has no fixeddimension. 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
valuesempty, 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
Nonefor a dense-only vector.metadata (dict[str, Any] | None) – Your own key-value pairs to filter on later, or
Noneif 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 isNoneis 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
valuesnorsparse_valuesis 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.
valuescomes 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 addsscore.DocumentRecord— the record type for schema-based indexes, which store JSON documents rather than raw vectors.- sparse_values: SparseValues | None¶
- static from_dict(vector_dict)[source]¶
Build a
Vectorfrom a plain dict.Accepts the snake_case keys
id,values,sparse_valuesandmetadata. Use it when your vectors arrive as dicts — from your own JSON, a dataframe row, or a previousto_dict()— and you want the same construction-time check thatVector(...)applies.- Parameters:
vector_dict (dict[str, Any]) – The dict to convert.
idis required; the rest are optional and default the same way the constructor does.- Returns:
Vectorwithsparse_valuesdecoded into aSparseValues.- Raises:
KeyError – If
idis absent.PineconeValueError – If neither
valuesnorsparse_valuesis populated.
- Return type:
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,StructOne match from a query: the vector that was found, plus how close it was.
Every element of
QueryResponse.matchesis one of these, soidandscoreare always populated.valuesandmetadataare not: a query omits both unless you ask for them, so an emptyvaluesor aNonemetadatausually 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 forcosineanddotproduct; lower is closer foreuclidean. 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 passinclude_values=True.sparse_values (SparseValues | None) – Sparse component of the matched vector, or
Nonefor a dense-only vector or when values were not requested.metadata (dict[str, Any] | None) – The metadata stored with the vector, or
Nonewhen the query did not passinclude_metadata=Trueor nothing was stored. Values follow the same grammar asVector.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.metadataisNoneeven 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"])
- sparse_values: SparseValues | None¶
- class pinecone.models.vectors.sparse.SparseValues(indices, values)[source]¶
Bases:
DictLikeStruct,StructA 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 declareddimension, 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_valueswhen upserting, and thesparse_vectorargument when querying.- Variables:
- 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}
- static from_dict(sparse_values_dict)[source]¶
Build a
SparseValuesfrom a plain dict.- Parameters:
sparse_values_dict (dict[str, Any]) – Dict with
indicesandvalueskeys, both required.- Returns:
SparseValuescarrying those two lists.- Raises:
KeyError – If either
indicesorvaluesis absent.- Return type:
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:
StructWhat one data-plane call cost, in read and write units.
Reachable as
usageon 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 reportsread_unitsand leaveswrite_unitsasNone.- Variables:
- Parameters:
- class pinecone.models.vectors.responses.QueryResponse(*, matches=<factory>, namespace='', usage=None, response_info=None)[source]¶
Bases:
DictLikeStruct,StructThe ranked matches a query found.
Almost everything you want is in
matches: a list ofScoredVector, already ordered somatches[0]is the closest hit. Read each match through.id,.score,.valuesand.metadata. The last two come back empty orNoneunless the query passedinclude_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
matchesrather 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
Noneif not reported.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif not populated.
- Parameters:
matches (list[ScoredVector])
namespace (str | None)
usage (Usage | None)
response_info (ResponseInfo | None)
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— whatsearchreturns instead, where the hits sit underresult.hitsand carryfieldsrather thanvaluesandmetadata.- matches: list[ScoredVector]¶
- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.responses.FetchResponse(*, vectors=<factory>, namespace='', usage=None, response_info=None)[source]¶
Bases:
DictLikeStruct,StructThe vectors a fetch retrieved, keyed by ID.
vectorsis 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
Noneif not reported.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif 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.- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.responses.FetchByMetadataResponse(*, vectors=<factory>, namespace='', usage=None, pagination=None, response_info=None)[source]¶
Bases:
DictLikeStruct,StructOne page of the vectors matching a metadata filter, keyed by ID.
Same shape as
FetchResponsepluspagination: 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 untilpaginationisNone.- Variables:
vectors (dict[str, Vector]) – Vector ID to
Vectorfor the matches on this page.namespace (str) – The namespace the vectors were fetched from.
usage (Usage | None) – Read units this page consumed, or
Noneif not reported.pagination (Pagination | None) – Token to pass as
pagination_tokenfor the next page, orNonewhen this is the last page.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif not populated.
- Parameters:
namespace (str)
usage (Usage | None)
pagination (Pagination | None)
response_info (ResponseInfo | None)
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.
- 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,StructWhat 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_sizethe client sends one request, soupserted_countis the whole answer and every batch counter is0. Withbatch_sizethe 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 anderrorsdescribe a partial success andupserted_countcovers only the batches that landed.- Variables:
upserted_count (int) – Vectors the server accepted. Equals
total_item_countwhen every batch succeeded, and for a non-batched call.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif not populated.total_item_count (int) – Vectors you submitted, across every batch.
0for 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.
0for 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:
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])
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_errorsbefore treatingupserted_countas the full count.failed_itemsflattens 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.- response_info: ResponseInfo | None¶
- errors: list[BatchError]¶
- property error_count: int¶
Alias for
failed_item_count, spelled asBatchResultspells it.
- property success_count: int¶
Alias for
upserted_count, spelled asBatchResultspells it.
- property successful_item_count: int¶
Alias for
upserted_count, spelled asBatchResultspells it.
- class pinecone.models.vectors.responses.UpdateResponse(*, matched_records=None, response_info=None)[source]¶
Bases:
DictLikeStruct,StructAcknowledgement that an update was accepted, and how many vectors it matched.
- Variables:
matched_records (int | None) – Vectors the update matched, or
Nonewhen no count was reported. A by-filter update is the case that reports one; passdry_run=Trueto 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
Noneif not populated.
- Parameters:
matched_records (int | None)
response_info (ResponseInfo | None)
- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.responses.ListResponse(*, vectors=<factory>, pagination=None, namespace='', usage=None, response_info=None)[source]¶
Bases:
StructDictMixin,StructOne page of vector IDs from a namespace.
Each element of
vectorsis aListItemcarrying only anid. The response is also directly iterable and sized, sofor item in responseandlen(response)walk that same page.- Variables:
pagination (Pagination | None) – Token for the next page, or
Nonewhen this is the last page.namespace (str) – The namespace the IDs were listed from.
usage (Usage | None) – Read units this page consumed, or
Noneif not reported.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif not populated.
- Parameters:
pagination (Pagination | None)
namespace (str)
usage (Usage | None)
response_info (ResponseInfo | None)
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.- pagination: Pagination | None¶
- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.responses.ListItem(*, id=None)[source]¶
Bases:
StructDictMixin,StructOne entry in
ListResponse.vectors— an ID and nothing else.listwalks 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.
- class pinecone.models.vectors.responses.Pagination(*, next=None)[source]¶
Bases:
StructDictMixin,StructThe cursor that carries you from one page of results to the next.
Appears as
paginationon every paged response. ANoneon the response, or aNoneinnext, 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, orNonewhen 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.
- 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,StructHow much is in an index, and how it is configured, as of this call.
The usual reason to call
describe_index_statsis to find out which namespaces exist and how many vectors each holds —namespacesanswers 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
Nonefor an index with no dense field.index_fullness (float) – How full the index is, from
0.0to1.0.total_vector_count (int) – Vectors across every namespace.
metric (str | None) – The similarity function used when ranking, e.g.
"cosine", orNoneif not reported.vector_type (str | None) –
"dense"or"sparse", orNoneif not reported.memory_fullness (float | None) – How full memory is, or
Noneif not reported.storage_fullness (float | None) – How full storage is, or
Noneif not reported.response_info (ResponseInfo | None) – HTTP response metadata (request ID, LSN values), or
Noneif 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]¶
- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.responses.NamespaceSummary(*, vector_count=0)[source]¶
Bases:
StructDictMixin,StructThe per-namespace entry in
DescribeIndexStatsResponse.
- class pinecone.models.vectors.responses.UpsertRecordsResponse(*, record_count, response_info=None)[source]¶
Bases:
StructDictMixin,StructAcknowledgement that
upsert_recordswas accepted.upsert_recordsembeds text server-side and the response body carries no counts, sorecord_countis what the client sent rather than what the server confirmed. Read it as “the request went out with this many records”, and calldescribe_index_statsif 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
Noneif not populated.
- Parameters:
record_count (int)
response_info (ResponseInfo | None)
- response_info: ResponseInfo | None¶
- class pinecone.models.response_info.BatchResponseInfo(*, lsn_reconciled=None, lsn_committed=None)[source]¶
Bases:
StructDictMixin,StructThe 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_headersand norequest_id: there is no single response to point at. When a sub-batch failed, its own exception is on that failure’serrorattribute in the result’serrorslist.- Variables:
- Parameters:
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
- 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.
- class pinecone.models.response_info.ResponseInfo(*, raw_headers=<factory>)[source]¶
Bases:
StructDictMixin,StructWhat 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_idis 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.
Nonewhen the header is absent.lsn_reconciled (int | None) – How far the index has caught up, as a log position.
Nonewhen the header is absent, so aNonehere means unknown, not position zero.lsn_committed (int | None) – Log position this write landed at.
Nonewhen the header is absent — including on reads, which commit nothing.
- Parameters:
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.- 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
Nonewhen 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_committedfrom an earlier write to find out whether that write is visible yet;is_reconciled()does the comparison for you.- Returns:
The reconciled position, or
Nonewhen the header is absent or not an integer.Nonemeans 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
Nonewhen 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_committedfrom an earlier write and get back whether the read that produced this response was able to see it.A
Falsemeans “not yet, as of this response” — it is a reason to read again, not an error.Falseis 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_committedof a prior upsert or delete. Guard against that beingNonebefore calling.- Returns:
Truewhenlsn_reconciledis known and at least target;Falseotherwise.- Return type:
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:
StructWhat 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 isTrue,errorsholds oneBatchErrorper 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
BatchErrorper failed batch.response_info (pinecone.models.response_info.BatchResponseInfo | None) – A
BatchResponseInfocarrying the log position the batch is durable through, orNonewhen no batch reported one. Use it to check that a later read sees these writes.timed_out (bool) – Whether a
total_timeoutexpired with work left unsent. The batches that were never attempted appear inerrors, sofailed_itemsis 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
Nonewhen the operation did not run through the gate. A value far below yourmax_concurrencymeans 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
errorswithdisposition="abandoned"; the gate itself re-probes after a cool-down.
- Parameters:
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)
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 )
- errors: list[BatchError]¶
- response_info: BatchResponseInfo | None¶
- 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.retryableisFalse— those fail identically on every attempt. Filtererrorson that flag instead when the retry is in a loop.- Returns:
A flat list of the items that did not land.
- class pinecone.models.batch.BatchError(*, batch_index, items, error, error_message, disposition='rejected', retryable=True)[source]¶
Bases:
StructOne 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
retryablebefore 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
BatchResultgroups 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.
Falsemarks a deterministic failure — a validation error, a 4xx rejection — that would fail identically every time. Filter on it before any retry loop.
- Parameters:
Search Models¶
- class pinecone.models.vectors.search.Hit(*, id_, score_, fields=<factory>)[source]¶
Bases:
StructDictMixin,StructOne search result: which record matched, how well, and the fields you asked for.
Read a hit as
hit.id,hit.scoreandhit.fields. The underscore-suffixedid_andscore_exist because the wire names are_idand_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"].fieldsholds your record’s own data, so what is in it depends on thefieldsargument the search passed — this is where a search differs from a query, which splits the same information acrossvaluesandmetadata.- 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
fieldsargument 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"])
- class pinecone.models.vectors.search.SearchResult(*, hits=<factory>)[source]¶
Bases:
StructDictMixin,StructThe 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.hitsand notresponse.hits.
- class pinecone.models.vectors.search.SearchRecordsResponse(*, result, usage, response_info=None)[source]¶
Bases:
StructDictMixin,StructWhat
searchreturns: the hits, nested one level down, plus what the call cost.The hits live at
response.result.hits— the extraresultstep is the shape of the response envelope, and forgetting it is the usual first stumble here. Each hit is aHit, read as.id,.scoreand.fields. A search that matched nothing returns an emptyhitslist 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
Noneif not populated.
- Parameters:
result (SearchResult)
usage (SearchUsage)
response_info (ResponseInfo | None)
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— whatqueryreturns instead, where the matches are atresponse.matchesand carryvaluesandmetadatarather thanfields.- result: SearchResult¶
- usage: SearchUsage¶
- response_info: ResponseInfo | None¶
- class pinecone.models.vectors.search.SearchInputs[source]¶
Bases:
dictThe
inputsargument ofsearch(), 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
RerankConfigit is aTypedDict, 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"}, )
- class pinecone.models.vectors.search.SearchUsage(*, read_units, embed_total_tokens=None, rerank_units=None)[source]¶
Bases:
StructDictMixin,StructWhat one search cost, broken out by the work it did.
Which fields are populated tells you which stages ran:
embed_total_tokensappears only when the index embedded your text, andrerank_unitsonly when you passedrerank. Both beingNoneis normal for a search that supplied its own vector.- Variables:
- Parameters:
- class pinecone.models.vectors.search.RerankConfig[source]¶
Bases:
dictThe
rerankargument ofsearch(), 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.modelandrank_fieldsare 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}, )
- class pinecone.models.vectors.search.SearchQuery(*, inputs, top_k, filter=None, vector=None, id=None, match_terms=None)[source]¶
Bases:
DictLikeStruct,StructQuery 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
Nonefor no filter.vector (dict[str, Any] | None) – Explicit query vector, or
Noneto 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:
- 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 areNone.- Return type:
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 areNone.- Return type:
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,StructExplicit dense/sparse query vector for search operations (legacy backcompat type).
- Variables:
- Parameters:
- 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 whenNone.- Return type:
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 whenNone.- Return type:
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,StructReranking 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
Noneto usetop_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
Noneto infer from inputs.
- Parameters:
- to_dict()[source]¶
Return a dict of non-None field values.
- Returns:
Dictionary containing only the fields whose value is not
None. Themodelfield is always present; optional fields (top_n,rank_fields,parameters,query) are omitted whenNone.- Return type:
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. Themodelfield is always present; optional fields (top_n,rank_fields,parameters,query) are omitted whenNone.- Return type:
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,StructOne merged ranking drawn from several namespaces, as
query_namespacesreturns it.Reads like a
QueryResponse:matchesis already interleaved and ordered, somatches[0]is the best hit found anywhere, and each element is aScoredVectoryou read as.id,.score,.valuesand.metadata. What it does not carry is anamespacefield, 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
metricthe 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]¶
- class pinecone.models.vectors.query_aggregator.QueryResultsAggregator(*, metric, top_k=10)[source]¶
Bases:
objectMerges per-namespace query responses into a single top-k ranking.
query_namespacesuses 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 withadd_results(), then callget_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:
cosineanddotproductrank higher scores first,euclideanranks 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:
- 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.- 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_kare dropped as you go, so adding many namespaces does not grow memory with the total number of matches.- Parameters:
namespace (str) – The namespace this response came from; used as the key in
QueryNamespacesResults.ns_usage, e.g."articles-en".response (QueryResponse) – What
queryreturned for that namespace.
- 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:
QueryNamespacesResultswithmatches(the merged top-k, best first),usage(read units summed over every namespace) andns_usage(read units per namespace).- Return type:
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:
objectOne document a search or fetch returned: its ID, its score, and your own fields.
Read the identifier as ``doc.id``.
doc._idreturns the same string and is kept so that code written against the wire shape keeps working, butdoc.idis the canonical spelling in this SDK and the one every example uses. The same holds fordoc.scoreoverdoc._score. The underscore forms belong to the JSON, not to your Python.Your own fields are reachable as attributes (
doc.title) and throughget(); which of them are present depends on theinclude_fieldsthe operation asked for. An absent field raisesAttributeErroron attribute access, so useget()when a field is optional.The
id,_id,scoreand_scoreproperties always win over a document field of the same name. If your data genuinely has a field called_score, reach it withdoc.get("_score")ordoc.to_dict()["_score"].- Variables:
id (str) – The document’s identifier — the value the document was upserted under.
score (float | None) – How well the document matched, or
Nonewhen the response carried no score. A fetch returns documents without scores, soNonethere is normal rather than a sign anything went wrong._score (float | None) – Alias for
score, matching the JSON key. Preferscore.
- Parameters:
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
- get(key, default=None)[source]¶
Read a field without risking
AttributeErrorif it is absent.Behaves like
dict.get()over the document. Reserved keys are readable here under their JSON names —get("_id")andget("_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:
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 —
_idand_score— alongside your own fields, which makes this the form to re-serialize or to feed to aDocumentRecord.
- class pinecone.models.documents.document.DocumentRecord(data=None, /, **fields)[source]¶
Bases:
objectA 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._idsits 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_vectortakes a list of floats, and one declaredsparse_vectortakes sparse values. Field values are checked against the index schema server-side, so a type mismatch surfaces on upsert rather than here.Only the
_idis validated on construction — a string of 1 to 512 ASCII characters — so a bad ID is reported at the line that wrote it.- Parameters:
- Raises:
ValueError – If
_idis 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
_idvisually 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
_idis the reserved key naming the document andtitleis 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.- get(key, default=None)[source]¶
Read a field, or the reserved
_id, without raising when it is absent.
- class pinecone.models.documents.document.UpdateDocumentRecord(data=None, /, **fields)[source]¶
Bases:
objectA 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:
_idsays which document to patch, and_remove_fieldslists 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:
- Raises:
ValueError – If
_idis missing or invalid, if_remove_fieldsis 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.
_idand_remove_fieldsare the two reserved keys here;titleis 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.- property remove_fields: list[str] | None¶
Field names this patch deletes, or
Nonewhen it only sets values.
- get(key, default=None)[source]¶
Read one entry of the patch, reserved keys included, without raising.
- class pinecone.models.documents.responses.ListedDocumentRecord(*, id)[source]¶
Bases:
StructOne 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 isentry.id;entry._idis the same value under the JSON key name.Examples
for entry in idx.documents.list(namespace="articles-en", prefix="article-"): print(entry.id)
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:
StructScore 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 intofieldswith aDeprecationWarningand this attribute reads back asNone, so readfieldswhichever way you set it.
- Raises:
ValueError – If
fieldsends up empty, or if bothfieldsandfieldare 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.
- class pinecone.models.documents.score_by.QueryStringQuery(*, query, field=None, fields=None)[source]¶
Bases:
StructScore documents by a Lucene query string, with
AND,ORandNOT.Choose this over
TextQuerywhen the query itself needs structure — combining terms, excluding one, or scoping a clause to one field. Fields are named inside the query string asfield_name:(clause); leave the qualifiers off and every text-searchable field is searched.- Variables:
- Raises:
ValueError – If
fieldorfieldsis 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'
- class pinecone.models.documents.score_by.DenseVectorQuery(*, field, values)[source]¶
Bases:
StructScore 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_vectorin the index schema, andvalueshas to be as long as that field’sdimension. A dense clause cannot be combined with any other scoring method in the same search.- Variables:
- Raises:
ValueError – If
fieldis empty, orvaluesis 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.
- class pinecone.models.documents.score_by.SparseVectorQuery(*, field, sparse_values)[source]¶
Bases:
StructScore 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_vectorin the index schema, and, like a dense clause, this one cannot be combined with any other scoring method in the same search.- Variables:
field (str) – The sparse vector field to score against, e.g.
"keywords".sparse_values (pinecone.models.vectors.sparse.SparseValues) – The query’s sparse vector, as
SparseValues.
- Raises:
ValueError – If
fieldis empty.- Parameters:
field (str)
sparse_values (SparseValues)
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.- sparse_values: SparseValues¶
Document Responses¶
- class pinecone.models.documents.responses.UpsertDocumentsResponse(*, upserted_count, response_info=None)[source]¶
Bases:
StructWhat a document upsert wrote.
- Variables:
upserted_count (int) – Documents the server accepted.
response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or
Nonewhen not present.
- Parameters:
upserted_count (int)
response_info (ResponseInfo | None)
- response_info: ResponseInfo | None¶
- class pinecone.models.documents.responses.SearchDocumentsResponse(matches, namespace, usage=None, response_info=None)[source]¶
Bases:
objectThe ranked documents a search found.
matchesis already ordered, somatches[0]is the best hit. Each element is aDocument: readdoc.idanddoc.score, then your own fields by name. Which fields are present depends on the search’sinclude_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 emptymatchesrather than raising.- Variables:
matches (list[pinecone.models.documents.document.Document]) – The matching documents, most relevant first.
namespace (str) – The namespace that was searched.
usage (pinecone.models.documents.responses.DocumentSearchUsage | None) – What the search cost, or
Nonewhen not returned.response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or
Nonewhen not present.
- Parameters:
namespace (str)
usage (DocumentSearchUsage | None)
response_info (ResponseInfo | None)
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)
- usage: DocumentSearchUsage | None¶
- response_info: ResponseInfo | None¶
- __init__(matches, namespace, usage=None, response_info=None)[source]¶
- Parameters:
namespace (str)
usage (DocumentSearchUsage | None)
response_info (ResponseInfo | None)
- 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:
response_info (ResponseInfo | None) – HTTP response metadata to attach, or
None. Keyword-only.
- Returns:
SearchDocumentsResponsewith oneDocumentper match.- Return type:
- class pinecone.models.documents.responses.FetchDocumentsResponse(documents, namespace, usage=None, pagination=None, response_info=None)[source]¶
Bases:
objectThe documents a fetch retrieved, keyed by ID.
documentsis 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:
documents (dict[str, pinecone.models.documents.document.Document]) – Document ID to
Document, for the requested IDs that exist.namespace (str) – The namespace the documents were fetched from.
usage (pinecone.models.documents.responses.DocumentFetchUsage | None) – What the fetch cost, or
Nonewhen not returned.pagination (pinecone.models.vectors.responses.Pagination | None) – Token for the next page of a fetch by filter, or
Nonewhen this is the last page. AlwaysNonefor a fetch by ID, which does not page.response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or
Nonewhen not present.
- Parameters:
namespace (str)
usage (DocumentFetchUsage | None)
pagination (Pagination | None)
response_info (ResponseInfo | None)
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])
- usage: DocumentFetchUsage | None¶
- pagination: Pagination | None¶
- response_info: ResponseInfo | None¶
- __init__(documents, namespace, usage=None, pagination=None, response_info=None)[source]¶
- Parameters:
namespace (str)
usage (DocumentFetchUsage | None)
pagination (Pagination | None)
response_info (ResponseInfo | None)
- 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:
response_info (ResponseInfo | None) – HTTP response metadata to attach, or
None. Keyword-only.
- Returns:
FetchDocumentsResponsekeyed by document ID.- Return type:
- class pinecone.models.documents.responses.ListDocumentsResponse(*, documents, namespace, usage, pagination=None, response_info=None)[source]¶
Bases:
StructOne decoded page of a document list, as it comes off the wire.
idx.documents.listdoes not hand this to you — it returns aPaginatorthat consumes these pages and yields theListedDocumentRecordentries, followingpaginationfor you. Read this model when you are driving the paging yourself.- Variables:
documents (list[pinecone.models.documents.responses.ListedDocumentRecord]) – The ID entries on this page, sorted by ID.
namespace (str) – The namespace the IDs were listed from.
usage (pinecone.models.documents.responses.DocumentListUsage) – What this page cost.
pagination (pinecone.models.vectors.responses.Pagination | None) – Token for the next page, or
Nonewhen this is the last page.response_info (pinecone.models.response_info.ResponseInfo | None) – HTTP response metadata (request ID and LSN headers), or
Nonewhen not present.
- Parameters:
documents (list[ListedDocumentRecord])
namespace (str)
usage (DocumentListUsage)
pagination (Pagination | None)
response_info (ResponseInfo | None)
See also
Pagination — which pagination shape applies where, and the paginator that saves you writing the loop.
- documents: list[ListedDocumentRecord]¶
- usage: DocumentListUsage¶
- pagination: Pagination | None¶
- response_info: ResponseInfo | None¶
- class pinecone.models.documents.responses.UpdateDocumentsResponse(*, matched_records=None, response_info=None)[source]¶
Bases:
StructConfirmation that a document update was accepted, and what it matched.
- Variables:
matched_records (int | None) – The number of documents that matched
filterwhen the update was accepted. Only returned for a filtered update —Nonefor 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
Nonewhen not present.
- Parameters:
matched_records (int | None)
response_info (ResponseInfo | None)
- response_info: ResponseInfo | None¶
- class pinecone.models.documents.responses.DeleteDocumentsResponse(*, matched_records=None, response_info=None)[source]¶
Bases:
StructConfirmation that a document delete was accepted, and what it matched.
- Variables:
matched_records (int | None) – The number of documents that matched
filterwhen the delete was accepted. Only returned for a filtered delete —Nonefor by-id and delete-all paths, and when the count could not be read in time.0means 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
Nonewhen not present.
- Parameters:
matched_records (int | None)
response_info (ResponseInfo | None)
- response_info: ResponseInfo | None¶
- class pinecone.models.documents.responses.DocumentSearchUsage(*, read_units)[source]¶
Bases:
StructWhat one document search cost.
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:
StructThe body of an
upsertonindex.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
DocumentRecordor a plain dict carrying the reserved_idkey alongside your own fields; either way the_idis 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
documentsis empty, holds more than 1000 documents, or contains a document whose_idis missing or invalid.- Parameters:
documents (list[dict[str, Any] | DocumentRecord])
- class pinecone.models.documents.requests.SearchDocumentsRequest(*, score_by, top_k, include_fields=None, filter=None)[source]¶
Bases:
StructThe body of a
searchonindex.documents.- Variables:
score_by (list[pinecone.models.documents.score_by.TextQuery | pinecone.models.documents.score_by.QueryStringQuery | pinecone.models.documents.score_by.DenseVectorQuery | pinecone.models.documents.score_by.SparseVectorQuery | dict[str, Any]]) – How to rank the documents, 1 to 100 clauses. Each may be a typed
DocumentScoringMethodvariant or a plain dict with atypekey. Severaltextandquery_stringclauses can be combined to score on more than one signal at once; adense_vectororsparse_vectorclause has to stand alone, and combining one with anything else is rejected here.top_k (int) – How many documents to return, 1 to 10000.
include_fields (list[str] | None) – Which of your fields to return on each match. Omitting it, and passing
[], both mean the same thing — only_idand_scorecome back. Pass["*"]for every field, or name the ones you need.filter (dict[str, Any] | None) – A metadata filter narrowing which documents are searched at all, or
Noneto search the whole namespace. It restricts the candidates; it does not contribute to the score.
- Raises:
ValueError – If
score_byis empty or holds over 100 clauses, if a vector clause is combined with another clause, or iftop_kis outside 1 to 10000.- Parameters:
score_by (list[TextQuery | QueryStringQuery | DenseVectorQuery | SparseVectorQuery | dict[str, Any]])
top_k (int)
- score_by: list[TextQuery | QueryStringQuery | DenseVectorQuery | SparseVectorQuery | dict[str, Any]]¶
- class pinecone.models.documents.requests.FetchDocumentsRequest(*, ids=None, filter=None, include_fields=None, pagination_token=None)[source]¶
Bases:
StructThe body of a
fetchonindex.documents.Select the documents one way or the other: exactly one of
idsandfiltermust be given. Only thefilterform 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
idsandfilterare given, iffilteris an empty object, ifidsholds over 1000 IDs, or ifpagination_tokenis given withoutfilter.- Parameters:
- class pinecone.models.documents.requests.ListDocumentsRequest(*, prefix=None, limit=None, pagination_token=None)[source]¶
Bases:
StructThe body of a
listonindex.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.Nonelists every ID.limit (int | None) – How many IDs per page, 1 to 100, or
Noneto let the server choose.pagination_token (str | None) – The token from a previous list response, to get the next page.
- Raises:
ValueError – If
prefixis over 512 characters or contains a non-ASCII character or NUL, or iflimitis outside 1 to 100.- Parameters:
- class pinecone.models.documents.requests.UpdateDocumentsRequest(*, documents=None, filter=None, set_fields=None, remove_fields=None)[source]¶
Bases:
StructThe body of an
updateonindex.documents, in either of its two forms.Patch named documents individually with
documents, or patch every document a filter matches withfilterplusset_fieldsand/orremove_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
UpdateDocumentRecordor a plain dict; in the dict form_idand_remove_fieldsare 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
filtermatches.remove_fields (list[str] | None) – Field names to delete from every document
filtermatches.
- Raises:
ValueError – If
documentsis combined with any by-filter field, if neither selector is given, ifset_fieldsorremove_fieldsis given without afilter, if afilteris given with nothing to change, iffilteris an empty object, or ifdocumentsis empty or holds over 1000 patches.- Parameters:
- class pinecone.models.documents.requests.DeleteDocumentsRequest(*, ids=None, filter=None, delete_all=None)[source]¶
Bases:
StructThe body of a
deleteonindex.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) –
Truedeletes every document in the namespace. Mutually exclusive with the others.
- Raises:
ValueError – If more than one selector is given, if none is, if
filteris an empty object, or ifidsholds over 1000 IDs.- Parameters:
Inference Models¶
- class pinecone.models.inference.embed.DenseEmbedding(*, values, vector_type='dense')[source]¶
Bases:
DictLikeStruct,StructOne embedding from a dense model, as a list of floats.
valuesis the vector, ready to pass toupsert()or as a query vector. Its length is the model’s output dimension, whichget_model()reports asdefault_dimension.- Variables:
- Parameters:
- class pinecone.models.inference.embed.SparseEmbedding(*, sparse_values, sparse_indices, sparse_tokens=None, vector_type='sparse')[source]¶
Bases:
StructDictMixin,StructOne embedding from a sparse model, stored as index/value pairs.
There is no
valuesfield here — the vector lives insparse_indicesandsparse_values, paired position by position. Reading.valueson one of these hands back a dict-view method rather than a vector and raises nothing to warn you, so branch on the enclosingEmbeddingsList’svector_typewhen the model is not fixed in advance.- Variables:
- Parameters:
- 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:
StructWhat
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:
model (str) – The model that served the request.
vector_type (str) –
"dense"or"sparse"— which ofDenseEmbeddingorSparseEmbeddingdataholds, and so which fields each item carries.data (list[pinecone.models.inference.embed.DenseEmbedding] | list[pinecone.models.inference.embed.SparseEmbedding]) – The embeddings themselves.
usage (pinecone.models.inference.embed.EmbedUsage) – Token usage, as
usage.total_tokens.
- Parameters:
model (str)
vector_type (str)
data (list[DenseEmbedding] | list[SparseEmbedding])
usage (EmbedUsage)
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'
- data: list[DenseEmbedding] | list[SparseEmbedding]¶
- usage: EmbedUsage¶
- class pinecone.models.inference.embed.EmbedUsage(*, total_tokens)[source]¶
Bases:
StructDictMixin,StructToken usage information for an embedding request.
- class pinecone.models.inference.rerank.RerankResult(*, model, data, usage)[source]¶
Bases:
StructWhat
rerank()returns.Bracket access with a field name (
result["model"]) reads the fields below. Returned by the SDK rather than constructed by callers.- Variables:
model (str) – The model that served the request, which is not always the one asked for — Pinecone may substitute a different model.
data (list[pinecone.models.inference.rerank.RankedDocument]) – The
RankedDocumentresults, ordered by descendingscorerather than by the order the documents were passed in.usage (pinecone.models.inference.rerank.RerankUsage) – Rerank usage, as
usage.rerank_units.
- Parameters:
model (str)
data (list[RankedDocument])
usage (RerankUsage)
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'
- data: list[RankedDocument]¶
- usage: RerankUsage¶
- class pinecone.models.inference.rerank.RankedDocument(*, index, score, document=None)[source]¶
Bases:
StructDictMixin,StructOne document and the score the reranker gave it.
indexis 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:
- Parameters:
- class pinecone.models.inference.rerank.RerankUsage(*, rerank_units)[source]¶
Bases:
StructDictMixin,StructUsage information for a rerank request.
- 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:
StructWhat one inference model is and what it will accept.
Returned by
get_model(), and bylist_models()for every model in the listing. The embed-only fields below areNoneon a reranking model, so readtypebefore 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 asname.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
ModelInfoSupportedParameterentries describing whatparameters=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
- supported_parameters: list[ModelInfoSupportedParameter]¶
- class pinecone.models.inference.models.ModelInfoSupportedParameter(*, parameter, type, value_type, required, allowed_values=None, min=None, max=None, default=None)[source]¶
Bases:
StructOne key a model accepts in a
parametersargument, and its bounds.Read these off
ModelInfo’ssupported_parametersto learn whatparameters=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:
- class pinecone.models.inference.model_list.ModelInfoList(models)[source]¶
Bases:
objectWhat
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
ModelInfoinstances.- Parameters:
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
- names()[source]¶
Return just the model identifiers, in listing order.
- Returns:
The
modelfield of eachModelInfo— the names accepted bymodel=onembed()andrerank().- Return type:
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']
- class pinecone.inference.models.index_embed.IndexEmbed(model, field_map, metric=None, read_parameters=<factory>, write_parameters=<factory>)[source]¶
Bases:
objectWhich model embeds an integrated index, and which field it embeds.
Accepted as the
embedargument ofcreate_index_for_model(), alongside a plain dict andEmbedConfig. Kept here, and importable frompinecone, for code written against earlier releases.- Parameters:
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,StructThe current state of one bulk import, as
describe_importreports 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:
statussays whether it is still running,percent_completesays how far along, andrecords_importedsays how much has actually landed. Poll untilstatusis a terminal value —Completed,Failed, orCancelled— and readerrorwhen it isFailed.- Variables:
id (str) – Identifier of the import, the value to pass back to
describe_importandcancel_import.uri (str) – Where the data is being read from.
status (str) –
Pending,InProgress,Failed,CompletedorCancelled. 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
Nonewhile it is still running.percent_complete (float | None) – How far along the import is, or
Nonebefore the server has a figure. Progress alone is not completion —statusis the authority.records_imported (int | None) – Records written so far, or
Nonebefore the server has a figure. AFailedimport 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 forFailed.
- Parameters:
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.
- class pinecone.models.imports.list.ImportList(imports, *, pagination=None)[source]¶
Bases:
objectOne page of
ImportModelobjects, iterable and sized like a list.What
list_imports_paginatedreturns. Iterate it, index into it, or takelen();paginationcarries the token for the next page, and isNonewhen this is the last one.- Variables:
pagination – Token for the next page, or
Nonewhen there are no more.- Parameters:
imports (list[ImportModel])
pagination (Pagination | None)
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
Nonewhen 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 fromImportModel.to_dict(). A"pagination"key is present only when there is a next page.- Return type:
Examples
>>> idx = pc.index(name="article-search") >>> idx.list_imports_paginated().to_dict() {'data': []}
- class pinecone.models.imports.model.StartImportResponse(*, id)[source]¶
Bases:
StructDictMixin,StructThe handle
start_importreturns: 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_importto pollImportModel, or tocancel_importto stop it.- Parameters:
id (str)
See also
How Bulk Ingest Behaves — the whole start-then-poll flow.
- class pinecone.models.imports.error_mode.ImportErrorMode(value)[source]¶
-
What a bulk import does when one record fails: skip it, or stop.
Pass this as
error_modeonstart_import. The choice is about how you would rather find out about bad data:ABORTsurfaces the first bad record immediately and imports nothing, which suits data you expect to be clean;CONTINUEloads 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,StructOne collection, as returned by
Collections.create(),Collections.describe(), and iteration overCollectionList.Only
name,status, andenvironmentare populated while the snapshot is still being built; readstatusbefore 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.
Noneuntil the collection is built.dimension (int | None) – Dimensionality of vectors in the collection, or
Noneuntil the collection is built.vector_count (int | None) – Number of vectors in the collection, or
Noneuntil the collection is built.
- Parameters:
Examples
>>> col = pc.collections.describe("movie-embeddings-snapshot") >>> col.status, col.dimension, col.vector_count ('Ready', 1024, 99)
- class pinecone.models.collections.list.CollectionList(collections)[source]¶
Bases:
objectThe collections in a project, as returned by
Collections.list().Iterating yields
CollectionModelobjects.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 byCollectionModel.to_dict().- Return type:
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']
- class pinecone.models.collections.description.CollectionDescription(name, source)[source]¶
Bases:
NamedTupleBasic metadata describing a collection.
- Variables:
- Parameters:
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:
StructOne 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
Nonewhile the source index is still active. An index-scoped listing only surfaces these rows when it is passedinclude_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
Nonewhen the server returns no schema (e.g. schedule-produced backups of an index that declared none). Legacy metadata-only schemas decode toLegacyMetadataFieldentries.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
Nonewhen the source index had none (the API returns"tags": nullrather 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)
created_at (str | None)
- schema: IndexSchema | None¶
- property dense_dimension: int | None¶
Dimension of the backup’s single dense vector field, if there is one.
Returns
Nonewhen the schema is absent, declares nodense_vectorfield, or declares more than one — in which case read the dimension off the field you want viaschema.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).schemabecomes a plain dict; legacy untyped schema fields are emitted without atypekey, matching the wire format.- Return type:
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:
objectOne 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:
backups (list[BackupModel])
pagination (Pagination | None)
- __init__(backups, *, pagination=None)[source]¶
Initialize a BackupList.
- Parameters:
backups (list[BackupModel]) – List of
BackupModelinstances representing index backups.pagination (Pagination | None) – Optional
Paginationtoken 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 byBackupModel.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:
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
nameset, itsbackup_idis used instead.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:
StructOne attempt at turning a backup back into an index.
Returned by
describe()andlist(); 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
Noneif the backend has not yet assigned a creation timestamp.completed_at (str | None) – Timestamp when the restore job completed, or
Noneuntil then.percent_complete (float | None) –
100oncestatusis"Completed", andNoneat every other point — it reports completion rather than progress, so it cannot drive a progress bar.
- Parameters:
- to_dict()[source]¶
Return a dict representation of this restore job model.
- Returns:
Dictionary with all fields, including optional ones that are
None(completed_atandpercent_complete). Values are not recursively converted.- Return type:
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:
objectOne 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:
restore_jobs (list[RestoreJobModel])
pagination (Pagination | None)
- __init__(restore_jobs, *, pagination=None)[source]¶
Initialize a RestoreJobList.
- Parameters:
restore_jobs (list[RestoreJobModel]) – List of
RestoreJobModelinstances representing restore operations.pagination (Pagination | None) – Optional
Paginationtoken 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 byRestoreJobModel.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:
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:
StructRequest model for creating an index from a backup.
Optionals you leave unset stay off the wire, so a request built with only
nameserialises 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:
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:
StructOne recurring backup cadence attached to an index.
Returned by every
BackupSchedulesmethod 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’sretention.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.NoneiffenabledisFalse: 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:
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.- to_dict()[source]¶
Return a dict representation of this schedule.
- Returns:
Dictionary with all fields, including
next_scheduled_runwhen it isNone. Timestamps are rendered back to RFC 3339 strings (normalised to UTCZform), so the result is JSON-serialisable.- Return type:
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:
objectOne page of an index’s backup schedules, plus its next-page token.
Returned by
list(); not constructed directly. Iteration,len(),names()andenabled_schedules()all read the page in hand only —iter_schedules()walks every page instead.- Parameters:
schedules (list[BackupScheduleModel])
pagination (Pagination | None)
- __init__(schedules, *, pagination=None)[source]¶
Initialize a BackupScheduleList.
- Parameters:
schedules (list[BackupScheduleModel]) – List of
BackupScheduleModelinstances representing the backup schedules on an index.pagination (Pagination | None) – Optional
Paginationtoken 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 byBackupScheduleModel.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:
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.
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:
- 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:
StructOne 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 plainstrso 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
Scheduledrow 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
statusis"Scheduled";Noneonce the run has started, andNoneon 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
Nonewhen the server reports none. Metadata-only schemas from older indexes decode toLegacyMetadataFieldentries.record_count (int | None) – Records in the snapshot.
0for aScheduledrow – 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 sendsnullrather than{}when there are none).
- Parameters:
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)
Note
name,record_count,namespace_countandsize_bytescan 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 backNone. Guard on them rather than assuming a value.- schema: IndexSchema | None¶
- class pinecone.models.backups.list.BackupScheduleHistoryList(items, *, pagination=None)[source]¶
Bases:
objectOne page of the backups a schedule has produced, plus its next-page token.
Returned by
history(); not constructed directly. Iteration,len()andscheduled()all read the page in hand only —iter_history()walks every page instead.- Parameters:
items (list[BackupScheduleHistoryItem])
pagination (Pagination | None)
- __init__(items, *, pagination=None)[source]¶
Initialize a BackupScheduleHistoryList.
- Parameters:
items (list[BackupScheduleHistoryItem]) – List of
BackupScheduleHistoryIteminstances representing backups produced by one schedule.pagination (Pagination | None) – Optional
Paginationtoken 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 byBackupScheduleHistoryItem.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:
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:
- class pinecone.models.backups.schedules.CreateBackupScheduleRequest(*, name, frequency, retention_days)[source]¶
Bases:
StructRequest model for creating a backup schedule.
Takes flat keyword arguments and builds the nested request body in
to_wire(), filling inschedule.typerather 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:
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
- class pinecone.models.backups.schedules.UpdateBackupScheduleRequest(*, frequency=None, retention_days=None, enabled=None)[source]¶
Bases:
StructRequest 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 into_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
namecannot 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", orNoneto leave it unchanged.retention_days (int | None) – New retention window in days, or
Noneto leave it unchanged. Must be at least 1; serialised asretention.expire_after_days. Changing it also re-times the pending deletions of backups this schedule already produced.enabled (bool | None) –
Falseto disable the schedule (clearing itsnext_scheduled_run),Trueto re-enable it, orNoneto 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 raisesConflictErrorif 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:
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
Namespace Models¶
- class pinecone.models.namespaces.models.NamespaceDescription(*, name='', record_count=0, schema=None, indexed_fields=None, size_bytes=0)[source]¶
Bases:
StructDictMixin,StructOne 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
Nonewhen 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)
- schema: NamespaceSchema | None¶
- indexed_fields: IndexedFields | None¶
- class pinecone.models.namespaces.models.ListNamespacesResponse(*, namespaces=<factory>, pagination=None, total_count=0)[source]¶
Bases:
StructDictMixin,StructOne page of namespace descriptions.
Iterable and sized directly, so
for ns in responseandlen(response)walk this page.total_countcounts every matching namespace, not just this page, so compare the two to tell whether more pages remain — or just followpaginationuntil it isNone.- Variables:
namespaces (list[pinecone.models.namespaces.models.NamespaceDescription]) – The
NamespaceDescriptionentries on this page.pagination (pinecone.models.vectors.responses.Pagination | None) – Token for the next page, or
Nonewhen this is the last page.total_count (int) – Namespaces matching the request, across every page.
- Parameters:
namespaces (list[NamespaceDescription])
pagination (Pagination | None)
total_count (int)
See also
Pagination — the paging loop used across the SDK.
- namespaces: list[NamespaceDescription]¶
- pagination: Pagination | None¶
- class pinecone.models.namespaces.models.NamespaceSchema(*, fields=<factory>)[source]¶
Bases:
StructDictMixin,StructWhich 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,StructWhether one metadata field is indexed for filtering.
filterabledefaults toFalseonly so a response decodes when the server omits the flag. As a request valueFalseis rejected — the only accepted value isTrue. To leave a field unindexed, omit it fromfieldsrather than sendingfilterable=False.
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
Pageonly when walking a listing page by page withPaginator.pages(); iterating aPaginatordirectly 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
Nonewhen this is the last page. A page truncated by the paginator’slimitalso reportsNonehere even though the server had more — resume fromPaginator.pagination_tokeninstead.
- Parameters:
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.
- 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. Useto_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 (
Nonefor the first page) and returns the matchingPage. 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;Nonestarts at the first page.limit (int | None) – Stop after this many items across all pages;
Nonewalks 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_paginatedinterface for vector IDs.- 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 isNoneonce the walk reaches the last page.
- pages()[source]¶
Walk the listing one
Pageat a time instead of item by item.When
limitis set, yields whole pages until the remaining budget is smaller than the next page, then yields that page truncated and stops. The truncated page reportspagination_token=None; to carry on later, resume from this paginator’s ownpagination_token, which still holds the server’s cursor.- Returns:
GeneratorofPage, each with anitemslist and apagination_tokennaming the page after it.- Return type:
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
Paginatoris onPinecone, this is onAsyncPinecone: 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 (
Nonefor the first page), returning the matchingPage. 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;Nonestarts at the first page.limit (int | None) – Stop after this many items across all pages;
Nonewalks 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.
- 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 isNoneonce the walk reaches the last page.
- async pages()[source]¶
Walk the listing one
Pageat a time instead of item by item.When
limitis set, yields whole pages until the remaining budget is smaller than the next page, then yields that page truncated and stops. The truncated page reportspagination_token=None; to carry on later, resume from this paginator’s ownpagination_token, which still holds the server’s cursor.- Returns:
AsyncGeneratorofPage, each with anitemslist and apagination_tokennaming 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]¶
-
Public cloud a managed index runs in.
Goes in the
cloudkey of a manageddeployment, and increate_for_model()’scloudargument. Pair it with a region enum for the same provider —AwsRegion,GcpRegion, orAzureRegion.- AWS = 'aws'¶
- GCP = 'gcp'¶
- AZURE = 'azure'¶
- class pinecone.models.enums.Metric(value)[source]¶
-
How similarity between two dense vectors is scored.
Set on the dense vector field in an index’s
schemaand fixed for the life of that field.COSINEcompares direction and ignores magnitude, which is what most text embedding models are trained for and the right default when in doubt.DOTPRODUCTtakes magnitude into account, and is the metric sparse fields always use.EUCLIDEANscores straight-line distance, so a smaller score is a closer match.- COSINE = 'cosine'¶
- EUCLIDEAN = 'euclidean'¶
- DOTPRODUCT = 'dotproduct'¶
- class pinecone.models.enums.VectorType(value)[source]¶
-
Dense or sparse, for the deprecated single-vector index shape.
Reaches the API only through the deprecated
vector_type=argument tocreate(). A currentschemanames adense_vectororsparse_vectorfield type instead, which is what lets one index hold both.- DENSE = 'dense'¶
- SPARSE = 'sparse'¶
- class pinecone.models.enums.DeletionProtection(value)[source]¶
-
Whether an index refuses to be deleted.
While
ENABLED,delete()on the index fails withForbiddenError, and you have toconfigureit back toDISABLEDfirst. New indexes areDISABLED.- ENABLED = 'enabled'¶
- DISABLED = 'disabled'¶
- class pinecone.models.enums.EmbedModel(value)[source]¶
-
Known embedding models for integrated indexes.
A convenience enum rather than an exhaustive list:
modelis also accepted as a plain string, so a model added after this SDK release can still be used. Calllist_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]¶
-
Known reranking models.
Like
EmbedModel, a convenience enum rather than an exhaustive list.Note
Pinecone_Rerank_V0is 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]¶
-
Pod hardware family and size, for the
pod_typeof a pod deployment.The family before the dot picks what the pod is optimized for —
s1for storage,p1for balanced performance,p2for query throughput — and thexNafter 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]¶
-
Environments for the
environmentof 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]¶
-
AWS regions for the
regionof a managed index oncloud="aws".A convenience enum rather than an exhaustive list, like
EmbedModel:regionalso 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]¶
-
Azure regions for the
regionof a managed index oncloud="azure".A convenience enum rather than an exhaustive list, like
EmbedModel:regionalso 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]¶
-
GCP regions for the
regionof a managed index oncloud="gcp".A convenience enum rather than an exhaustive list, like
EmbedModel:regionalso 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,StructResponse 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
Nonewhen 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:
id (str)
name (str | None)
project_id (str)
roles (list[APIKeyRole])
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
APIKeyWithSecret— whatApiKeys.create()returns instead, wrapping this model alongside the secret it shows only once.
- roles: list[APIKeyRole]¶
- property role: APIKeyRole¶
Singular alias for
roleswhen the key has exactly one role.- Returns:
The single role assigned to this key.
- Return type:
- 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:
objectThe API keys of one project, as returned by a list call.
A sequence of
APIKeyModel— iterable, indexable, and sized — withnames()andto_dict()on top. Not constructed directly; it is whatApiKeys.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
APIKeyModelinstances 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 byAPIKeyModel.to_dict().- Return type:
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
Nonefor keys whose backend display label is unset.
- Return type:
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,StructResponse 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
idevery other API-key operation takes.value (str) – The secret API key string — what
Pineconeis constructed with. Treat as a credential.
- Parameters:
key (APIKeyModel)
value (str)
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 returnvaluein full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.- key: APIKeyModel¶
- class pinecone.models.admin.api_key.APIKeyRole(value)[source]¶
-
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
strenum, 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,StructResponse 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
Adminclient’s credentials resolve to exactly one organization, so most admin operations never need thisid.- 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
ForbiddenErrornaming 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'
- class pinecone.models.admin.organization.OrganizationList(organizations)[source]¶
Bases:
objectThe organizations reachable with the current credentials.
A sequence of
OrganizationModel— iterable, indexable, and sized — withnames()andto_dict()on top. Not constructed directly; it is whatOrganizations.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
OrganizationModelinstances 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 byOrganizationModel.to_dict().- Return type:
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', ...}]}
- class pinecone.models.admin.project.ProjectModel(*, id, name, max_pods, force_encryption_with_cmek, organization_id, created_at=None)[source]¶
Bases:
StructDictMixin,StructResponse 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
idis the only safe way to refer to one.- Variables:
id (str) – Unique identifier for the project. This is the
resource_ida project-scoped role binding takes, and theproject_idthe 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
Nonewhen the server omits it.
- Parameters:
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'
- class pinecone.models.admin.project.ProjectList(projects)[source]¶
Bases:
objectThe projects of the organization the credentials resolve to.
A sequence of
ProjectModel— iterable, indexable, and sized — withnames()andto_dict()on top. Not constructed directly; it is whatProjects.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
ProjectModelinstances 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 byProjectModel.to_dict().- Return type:
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', ...}]}
- class pinecone.models.admin.token.TokenResponse(*, access_token, token_type=None, expires_in=None)[source]¶
Bases:
StructDictMixin,StructResponse model for the OAuth2 client-credentials token exchange.
Adminperforms 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’sclient_idandclient_secretare 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, andNonewhen the server omits the field.expires_in (int | None) – Seconds until the token expires, or
Nonewhen 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:
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 ofaccess_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 returnaccess_tokenin full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.
- class pinecone.models.admin.pagination.PaginationResponse(*, next=None)[source]¶
Bases:
StructDictMixin,StructCursor envelope returned by paginated Admin API list responses.
- Variables:
next (str | None) – Opaque cursor for the next page, or
Nonewhen the server did not supply one. The value is never parsed or constructed by the SDK — pass it back verbatim as thepagination_tokenargument on the following list call.- Parameters:
next (str | None)
Examples
>>> from pinecone.models.admin.pagination import PaginationResponse >>> page = PaginationResponse(next="eyJsYXN0X2lkIjoiZTJlOTI1MjMifQ==") >>> page.next 'eyJsYXN0X2lkIjoiZTJlOTI1MjMifQ=='
- class pinecone.models.admin.user.UserModel(*, id, email, name=None)[source]¶
Bases:
StructDictMixin,StructResponse 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()withprincipal_type="user"and thisidasprincipal_id.- Variables:
id (str) – Unique identifier (UUID) for the user. This is the
principal_idrole-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
Nonewhen 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 astatus.
- class pinecone.models.admin.user.UserList(*, data=<factory>, pagination=None)[source]¶
Bases:
StructA 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 aPaginatorinstead, which follows these cursors for them.- Variables:
pagination (PaginationResponse | None) – Cursor envelope for the next page, or
Noneon the final page.
- Parameters:
pagination (PaginationResponse | None)
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']
- pagination: PaginationResponse | None¶
- class pinecone.models.admin.invite.InviteModel(*, id, email, status, expires_at=None, processed_at=None, created_at)[source]¶
Bases:
StructDictMixin,StructResponse model for an invitation to join the organization.
statusis typed asstrrather thanInviteStatusso a status added by the server after this SDK release surfaces as its raw string instead of raising. Compare againstInviteStatusmembers directly — they arestrvalues.- Variables:
id (str) – Unique identifier (UUID) for the invite.
email (str) – The email address the invite was sent to.
status (str) – One of the
InviteStatusvalues.expires_at (str | None) – RFC 3339 timestamp for when the invite expires if not accepted, or
Noneif 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:
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’sidis not usable as a user ID.
- class pinecone.models.admin.invite.InviteList(*, data=<factory>, pagination=None)[source]¶
Bases:
StructA 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 aPaginatorinstead, 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
Noneon the final page.
- Parameters:
data (list[InviteModel])
pagination (PaginationResponse | None)
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¶
- class pinecone.models.admin.invite.InviteStatus(value)[source]¶
-
The lifecycle status of an organization invite.
Possible values:
pending,expired,processed.List operations return only
pendingandexpiredinvites;processedis 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,StructResponse 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()withprincipal_type="service_account"and thisidasprincipal_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_idwhen 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
idis 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
ServiceAccountWithSecret— whatServiceAccounts.create()andServiceAccounts.rotate_secret()return instead, wrapping this model alongside the one-time secret.UserModel— the human equivalent, which has an email address rather than OAuth credentials.
- class pinecone.models.admin.service_account.ServiceAccountList(*, data=<factory>, pagination=None)[source]¶
Bases:
StructA 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 aPaginatorinstead, 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
Noneon the final page.
- Parameters:
data (list[ServiceAccountModel])
pagination (PaginationResponse | None)
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¶
- class pinecone.models.admin.service_account.ServiceAccountWithSecret(*, service_account, client_secret)[source]¶
Bases:
StructDictMixin,StructResponse model for a service account with a newly issued OAuth secret.
Returned only by
ServiceAccounts.create()andServiceAccounts.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
idevery other service-account operation takes.client_secret (str) – The OAuth client secret. Treat as a credential.
- Parameters:
service_account (ServiceAccountModel)
client_secret (str)
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 returnclient_secretin full, so a result serialized wholesale into a log line, an error report, or a cache writes the live credential out.- service_account: ServiceAccountModel¶
- class pinecone.models.admin.role_binding.RoleBindingModel(*, id, principal_type, principal_id, resource_type, resource_id, role, created_at)[source]¶
Bases:
StructDictMixin,StructResponse model for a role binding: a
rolegranted to a principal at a scope.principal_type,resource_type, androleare typed asstrrather than as enums so values the server adds after this SDK release surface as their raw strings instead of raising. Compare againstPrincipalType,ResourceType, andRoleNamedirectly — they arestrvalues.- 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
PrincipalTypevalues.principal_id (str) – The principal’s UUID.
resource_type (str) – One of the
ResourceTypevalues.resource_id (str) – The organization or project the binding is scoped to. Always populated, including on organization-scoped bindings whose create request omitted it.
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:
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
- class pinecone.models.admin.role_binding.RoleBindingList(*, data=<factory>, pagination=None)[source]¶
Bases:
StructA 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 aPaginatorinstead, which follows these cursors for them.- Variables:
data (list[RoleBindingModel]) – The role bindings on this page.
pagination (PaginationResponse | None) – Cursor envelope for the next page, or
Noneon the final page.
- Parameters:
data (list[RoleBindingModel])
pagination (PaginationResponse | None)
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¶
- class pinecone.models.admin.role_binding.RoleBindingInput(*, resource_type, role, resource_id=None)[source]¶
Bases:
StructDictMixin,StructA role to grant when creating an invite or a service account.
Unlike the response models, this is an input the SDK sends, so
resource_typeandroleare validated on construction against the values this SDK release knows about.resource_typeselects the binding scope. Fororganizationscope, omitresource_id— the binding applies to the organization inferred from the request context. Forprojectscope,resource_idis required and must be the project UUID.- Variables:
resource_type (str) – One of the
ResourceTypevalues.resource_id (str | None) – The project UUID for
projectscope; leave unset fororganizationscope.
- Raises:
PineconeValueError – If
resource_typeorroleis not a recognized value, or ifresource_typeisprojectandresource_idis missing or empty. Raised at construction, so a malformed binding fails before the call that would have sent it.- Parameters:
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 ownidand the principal.RoleBindings.create()— grants a role to an existing principal, taking the same fields as keyword arguments rather than as this struct.
- class pinecone.models.admin.role_binding.RoleName(value)[source]¶
-
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
ForbiddenErrorat 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]¶
-
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]¶
-
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,StructResponse 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
Noneif not returned by the API.updated_at (str | None) – ISO 8601 timestamp when the assistant was last updated, or
Noneif not returned by the API.metadata (dict[str, Any] | None) – Optional metadata dictionary associated with the assistant, or
Noneif not set.instructions (str | None) – Optional description or directive for the assistant to apply to all responses, or
Noneif not set.host (str | None) – The host where the assistant is deployed, or
Noneif not yet available.region (str | None) – The region the assistant is deployed in (
"us"or"eu"), orNoneif not returned by the API.
- Parameters:
- 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,StructResponse 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-07this 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
Noneif 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"), orNone.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
Nonewhen not requested or unavailable.content_hash (str | None) – Hash of the file content (wire key
crc32c_hash), orNonewhen not available. Legacy callers can also access this value via thecrc32c_hashproperty alias.
- Parameters:
percent_doneanderror_messagewere removed in the2026-07API; accessing them raises anAttributeErrornamingdescribe_operationas the replacement.- property crc32c_hash: str | None¶
Backwards-compatibility alias for
content_hash.
- class pinecone.models.assistant.list.ListAssistantsResponse(*, assistants, pagination=None)[source]¶
Bases:
StructDictMixin,StructOne page of assistants, plus the token for the next one.
Returned by
list_page(). This is one page only — passnextback aspagination_tokento advance, or calllist(), which drives that loop for you and yields assistants directly.- Variables:
assistants (list[pinecone.models.assistant.model.AssistantModel]) – The
AssistantModelobjects on this page.pagination (pinecone.models.assistant.list._Pagination | None) – The raw nested wire object. Read
nextinstead.
- Parameters:
assistants (list[AssistantModel])
pagination (_Pagination | None)
Examples
nextisNoneon 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]¶
- class pinecone.models.assistant.list.ListFilesResponse(*, files, pagination=None)[source]¶
Bases:
StructDictMixin,StructOne page of an assistant’s files, plus the token for the next one.
Returned by
list_files_page(). This is one page only — passnextback aspagination_tokento advance, or calllist_files(), which drives that loop for you and yields files directly.- Variables:
files (list[pinecone.models.assistant.file_model.AssistantFileModel]) – The
AssistantFileModelobjects on this page.pagination (pinecone.models.assistant.list._Pagination | None) – The raw nested wire object. Read
nextinstead.
- Parameters:
files (list[AssistantFileModel])
pagination (_Pagination | None)
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]¶
- 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,StructResponse 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_onanderror_message; the rename mapping presents them asoperation_id,created_atanderrorin Python for clarity. Every other attribute carries its wire name.Every field except
operation_idandstatusis optional so that the smaller body shipped by the2026-04upsert path still decodes. The server omitscompleted_on,error_messageandingestion_unitswhile they do not apply; a spec-conformant server may instead send them asnull. Both decode toNone.- 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 (seeerror).operation_type (str | None) – The kind of action this operation represents —
"upload_file","upsert_file","update_file_metadata"or"delete_file"— orNonewhen 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
Nonewhilestatusis"Processing".percent_complete (int | None) – Progress of the operation as a percentage from 0 to 100, or
Nonewhen 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 withCOALESCE, 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 whenstatusis"Failed".ingestion_units (float | None) – Ingestion units consumed by this operation, reported once a file ingestion operation has completed, or
None.
- Parameters:
- class pinecone.models.assistant.list.ListOperationsResponse(*, operations, pagination=None)[source]¶
Bases:
StructDictMixin,StructOne page of an assistant’s operations, plus the token for the next one.
Returned by
list_operations_page(). This is one page only — passnextback aspagination_tokento advance, or calllist_operations(), which drives that loop for you and yields operations directly.- Variables:
operations (list[pinecone.models.assistant.operation.OperationModel]) – The
OperationModelobjects on this page.pagination (pinecone.models.assistant.list._Pagination | None) – The raw nested wire object. Read
nextinstead.
- Parameters:
operations (list[OperationModel])
pagination (_Pagination | None)
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]¶
- class pinecone.models.assistant.message.Message(*, content, role='user')[source]¶
Bases:
StructDictMixin,StructA 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:
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,StructThe generated answer to a chat request, with its citations.
Returned by
chat()whenstreamis leftFalse. The answer text is atresponse.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 isresponse.citations[i].references[j].file.name, withcitations[i].positionsaying 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) –
ChatUsagetoken counts for the request.message (pinecone.models.assistant.chat.ChatMessage) – The assistant’s reply as a
ChatMessage; the text is atmessage.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
ChatCitationentries tying positions inmessage.contentto 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
Noneif the server did not report it.0means 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
Nonewhen the provider returned none. Readspecfor the provider’s name andresultsfor 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=Truetochat()to get the source passage as well as the file name.See also
ContextResponse— the retrieved snippets with no answer generated over them, fromcontext(). 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, fromchat(..., stream=True).
- message: ChatMessage¶
- citations: list[ChatCitation]¶
- class pinecone.models.assistant.chat.ChatMessage(*, role, content)[source]¶
Bases:
StructDictMixin,StructThe assistant’s reply inside a
ChatResponse.Reached as
response.message. To send a message, build aMessageinstead — this class only comes back from the API.- Variables:
- Parameters:
- class pinecone.models.assistant.chat.ChatCitation(*, position, references)[source]¶
Bases:
StructDictMixin,StructA point in the answer, tied to the documents that support it.
Reached as an entry of
response.citationson aChatResponse, or aschunk.citationon aStreamCitationChunk.- Variables:
position (int) – Character position in
response.message.contentthat this citation annotates. Insert a footnote marker there to render the answer with inline sources.references (list[pinecone.models.assistant.chat.ChatReference]) – The
ChatReferenceentries supporting the answer at that position. Can hold more than one document.
- Parameters:
position (int)
references (list[ChatReference])
- references: list[ChatReference]¶
- class pinecone.models.assistant.chat.ChatReference(*, file, pages=None, highlight=None)[source]¶
Bases:
StructDictMixin,StructOne 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:
file (pinecone.models.assistant.file_model.AssistantFileModel) – The source file, as an
AssistantFileModel—file.namefor a label,file.idto fetch it again, andfile.metadatafor whatever you attached at upload.pages (list[int] | None) – Page numbers within the source file, for paginated documents such as PDFs.
Nonefor sources that have no pages.highlight (pinecone.models.assistant.chat.ChatHighlight | None) – The
ChatHighlightpassage this reference drew on, orNoneunless the chat request setinclude_highlights=True.
- Parameters:
file (AssistantFileModel)
highlight (ChatHighlight | None)
- file: AssistantFileModel¶
- highlight: ChatHighlight | None¶
- class pinecone.models.assistant.chat.ChatHighlight(*, type, content)[source]¶
Bases:
StructDictMixin,StructThe passage of a source document that a citation drew on.
Reached as
reference.highlight, and present only when the chat request setinclude_highlights=True. Render it to show the reader the source text behind a citation without fetching the file.- Variables:
- Parameters:
- class pinecone.models.assistant.chat.ChatUsage(*, prompt_tokens, completion_tokens, total_tokens)[source]¶
Bases:
StructDictMixin,StructToken counts the API reported for one assistant request.
Reached as
usageonChatResponse,ChatCompletionResponse,ContextResponse,AlignmentResult, and on the closing chunk of a stream.- Variables:
- Parameters:
- class pinecone.models.assistant.chat.ChatCompletionResponse(*, id, model, usage, choices)[source]¶
Bases:
StructDictMixin,StructThe generated answer to a chat request, in OpenAI-compatible shape.
Returned by
chat_completions()whenstreamis leftFalse. The answer text is nested atresponse.choices[0].message.content. There is no structured citation list here; citations arrive woven into the answer text, so preferChatResponseunless you are pointing existing OpenAI client code at Pinecone.- Variables:
id (str) – Identifier of this completion.
model (str) – Name of the model that generated the answer, which need not be the name you requested.
usage (pinecone.models.assistant.chat.ChatUsage) –
ChatUsagetoken counts for the request.choices (list[pinecone.models.assistant.chat.ChatCompletionChoice]) – The
ChatCompletionChoiceanswers, normally one. Read the text fromchoices[0].message.content.
- Parameters:
id (str)
model (str)
usage (ChatUsage)
choices (list[ChatCompletionChoice])
Examples
The text is two levels down, under
choices, and there is nocitationsattribute to read — that absence is the whole difference fromChatResponse:>>> 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, whosecitationsare objects you can render as source links.ChatCompletionStream— the same answer delivered as chunks, fromchat_completions(..., stream=True).
- choices: list[ChatCompletionChoice]¶
- class pinecone.models.assistant.chat.ChatCompletionChoice(*, index, message, finish_reason)[source]¶
Bases:
StructDictMixin,StructA single answer in a chat completion response.
Reached as
response.choices[0].- Variables:
index (int) – Position of this choice in the response’s
choiceslist.message (pinecone.models.assistant.chat.ChatCompletionMessage) – The
ChatCompletionMessagefor this choice; the text is atmessage.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)
- message: ChatCompletionMessage¶
- class pinecone.models.assistant.chat.ChatCompletionMessage(*, role=None, content=None)[source]¶
Bases:
StructDictMixin,StructThe answer message inside a chat completion choice.
Reached as
response.choices[0].message. Both fields are optional, so guard oncontentbefore using it.- Variables:
- Parameters:
Assistant Context Models¶
- class pinecone.models.assistant.context.ContextResponse(*, snippets, usage, id=None)[source]¶
Bases:
StructDictMixin,StructThe 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.snippetsholdsContextSnippet, which is two classes. ATextSnippethas a stringcontent. AMultimodalSnippethas a list of blocks instead — each aContextTextBlock(block.text) or aContextImageBlock(block.caption, plusblock.image_datawhen the request setinclude_binary_content=True). Branch withisinstance, not on atypeattribute: the snippet and block classes do not re-expose their wire tag, sosnippet.typeraisesAttributeError. Both snippet classes carryscoreandsnippet.reference.file.name.- Variables:
snippets (list[pinecone.models.assistant.context.TextSnippet | pinecone.models.assistant.context.MultimodalSnippet]) – The retrieved snippets.
usage (pinecone.models.assistant.chat.ChatUsage) –
ChatUsagetoken counts for the retrieval request.id (str | None) – Identifier of this context response, or
Nonewhen the server did not report one.
- Parameters:
snippets (list[TextSnippet | MultimodalSnippet])
usage (ChatUsage)
id (str | None)
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.typeto 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, fromchat(), with citations you can render.ContextOptions— the bundle that tunes retrieval for a chat request.
- snippets: list[TextSnippet | MultimodalSnippet]¶
- class pinecone.models.assistant.options.ContextOptions(*, top_k=None, snippet_size=None, multimodal=None, include_binary_content=None)[source]¶
Bases:
StructDictMixin,StructOptions 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;
0and 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:
- 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
typetag.Both variants carry
scoreandreference; they differ incontent. On aTextSnippetit is a string; on aMultimodalSnippetit 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, sosnippet.typeraisesAttributeError.
- class pinecone.models.assistant.context.TextSnippet(*, content, score, reference)[source]¶
Bases:
StructDictMixin,StructA retrieved passage of plain text, from the wire tag
"text".The
ContextSnippetvariant whosecontentis a single string. A request withmultimodal=Truecan instead yield aMultimodalSnippet, whosecontentis a list of blocks, so branch withisinstancebefore readingcontent.Branching on the tag instead gives you
AttributeError: 'TextSnippet' object has no attribute 'type'. That does not mean the payload lacked atype: 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:
content (str) – The retrieved passage, ready to put in your own prompt.
score (float) – Relevance of the snippet to the query; higher is more relevant.
reference (pinecone.models.assistant.context.FileReference) – The
FileReferencenaming where the passage came from.
- Parameters:
content (str)
score (float)
reference (FileReference)
- reference: FileReference¶
- class pinecone.models.assistant.context.MultimodalSnippet(*, content, score, reference)[source]¶
Bases:
StructDictMixin,StructA retrieved passage of mixed text and images, wire tag
"multimodal".The
ContextSnippetvariant whosecontentis a list of blocks rather than a string, so iterate it and branch withisinstanceonContextTextBlockversusContextImageBlock.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 atype: the tag selected the class during decoding and was then dropped, so there is no attribute to read.- Variables:
content (list[pinecone.models.assistant.context.ContextTextBlock | pinecone.models.assistant.context.ContextImageBlock]) – The blocks making up the snippet, in document order. Each is a
ContextTextBlock(readblock.text) or aContextImageBlock(readblock.caption, andblock.image_datawhen the request setinclude_binary_content=True).score (float) – Relevance of the snippet to the query; higher is more relevant.
reference (pinecone.models.assistant.context.FileReference) – The
FileReferencenaming where the passage came from.
- Parameters:
content (list[ContextTextBlock | ContextImageBlock])
score (float)
reference (FileReference)
- content: list[ContextTextBlock | ContextImageBlock]¶
- 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
isinstanceand readblock.texton aContextTextBlockorblock.captionon aContextImageBlock. These classes do not re-expose the wire tag, soblock.typeraisesAttributeError.
- class pinecone.models.assistant.context.ContextTextBlock(*, text)[source]¶
Bases:
StructDictMixin,StructText inside a
MultimodalSnippet, wire tag"text".Identify it with
isinstance;block.typegives youAttributeError: '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
texthere, not thecontentthatTextSnippetuses.- Parameters:
text (str)
- class pinecone.models.assistant.context.ContextImageBlock(*, caption, image_data=None)[source]¶
Bases:
StructAn 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.typegives youAttributeError: 'ContextImageBlock' object has no attribute 'type', because the tag selected this class during decoding and was then dropped.- Variables:
caption (str) – A text caption describing the image. Usable in a prompt on its own, without the image bytes.
image_data (pinecone.models.assistant.context.ContextImageData | None) – The
ContextImageDataholding the encoded image, orNonewhen the request did not setinclude_binary_content=True.
- Parameters:
caption (str)
image_data (ContextImageData | None)
- image_data: ContextImageData | None¶
- class pinecone.models.assistant.context.ContextImageData(*, type, mime_type, data)[source]¶
Bases:
StructDictMixin,StructThe encoded bytes of an image in a multimodal context snippet.
Reached as
block.image_data, and present only when the request setinclude_binary_content=True.datais text, not bytes — decode it before writing a file.- Variables:
- Parameters:
- pinecone.models.assistant.context.ContextReference¶
Alias for
FileReference, the type ofsnippet.reference.
- class pinecone.models.assistant.context.FileReference(*, file, pages=None, type=None)[source]¶
Bases:
StructDictMixin,StructThe source file a context snippet came from.
Reached as
snippet.reference. Renderreference.file.nameas the label andreference.pagesto point at the part of the document used.- Variables:
file (pinecone.models.assistant.file_model.AssistantFileModel) – The source file, as an
AssistantFileModel—file.namefor a label,file.idto fetch it again, andfile.metadatafor 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.
Nonefor text, JSON, or Markdown sources.type (str | None) – The kind of document referenced —
"text","json","markdown","pdf", or"doc_x"— orNonewhen the payload omits it.
- Parameters:
file (AssistantFileModel)
type (str | None)
- file: AssistantFileModel¶
- pinecone.models.assistant.context.PageReference¶
Alias kept for backwards compatibility. Use
FileReferenceinstead.
Assistant Evaluation Models¶
- class pinecone.models.assistant.evaluation.AlignmentResult(*, scores, facts, usage)[source]¶
Bases:
StructDictMixin,StructHow well a generated answer matched a ground-truth answer.
Returned by
evaluate_alignment(). Readresult.scoresfor the aggregate numbers andresult.factsfor the per-fact judgments that explain them — the scores tell you an answer is wrong, and the facts tell you where.- Variables:
scores (pinecone.models.assistant.evaluation.AlignmentScores) – The
AlignmentScoresfor the answer as a whole —scores.correctness(precision of what the answer said),scores.completeness(recall against the ground truth), andscores.alignment, their harmonic mean. Read all three: a low score on either input drags the mean down.facts (list[pinecone.models.assistant.evaluation.EntailmentResult]) – An
EntailmentResultper fact, each with a judgment and the reasoning behind it.usage (pinecone.models.assistant.chat.ChatUsage) –
ChatUsagetoken counts for the evaluation request itself, not for the answer being evaluated.
- Parameters:
scores (AlignmentScores)
facts (list[EntailmentResult])
usage (ChatUsage)
Examples
The answer below contradicts the ground truth, so the scores come back low and
factsrecords 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]¶
- class pinecone.models.assistant.evaluation.AlignmentScores(*, correctness, completeness, alignment)[source]¶
Bases:
StructDictMixin,StructThe three aggregate scores of an alignment evaluation.
Reached as
result.scores. Becausealignmentis a harmonic mean, a low score on either input drags it down, so read all three rather than trackingalignmentalone.- Variables:
- Parameters:
- class pinecone.models.assistant.evaluation.EntailmentResult(*, fact, entailment, reasoning='')[source]¶
Bases:
StructDictMixin,StructOne 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 asstrrather 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 forNone.
- Parameters:
Assistant Streaming Models¶
- class pinecone.models.assistant.streaming.ChatStream(stream)[source]¶
Bases:
objectA Pinecone-native chat stream, returned by
chat(..., stream=True).Iterating it yields the
ChatStreamChunkvariants, which is the only way to reach citations and token usage.text()andcollect()skip the dispatch and hand you text alone. The stream is single-pass: iterating,text(), andcollect()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
ChatStreamChunk— the four chunk types, and the loop to write when you need citations rather than text alone.ChatCompletionStream— the same request in the OpenAI-compatible shape, fromchat_completions().AsyncChatStream— theAsyncPineconeequivalent.
- 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.contentof eachStreamContentChunk, 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:
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
StreamContentChunkfragment joined in arrival order. Citations and token usage are discarded along with the other chunk types — iterate the stream itself for those.- Return type:
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
typefield.Iterating a
ChatStreamyields these four classes, and branching on which one arrived is the whole contract. Each also exposes its tag aschunk.type, so a caller can dispatch onisinstanceor on the string.StreamMessageStart(type == "message_start")Arrives once, first. No response text.
model,role, andcontext_snippet_count— a0there 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.positionis a character position in the response text, and each ofchunk.citation.referenceshasreference.file.name,reference.pages, andreference.highlight.StreamMessageEnd(type == "message_end")Arrives once, last. No response text.
usagetoken counts andfinish_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 underchoicesand whose citations are woven into the text rather than delivered as objects.
- class pinecone.models.assistant.streaming.ChatCompletionStream(stream)[source]¶
Bases:
objectAn OpenAI-compatible stream, from
chat_completions(..., stream=True).Iterating it yields
ChatCompletionStreamChunk, whose text sits atchunk.choices[0].delta.contentand can beNoneor""on the role-only first chunk and the finish chunk;text()andcollect()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(), andcollect()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— theAsyncPineconeequivalent.
- 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.contentof each chunk that has one, in arrival order. Chunks whose content isNoneor"", and chunks with an emptychoiceslist, are skipped, as isusageon the final chunk — iterate the stream itself for that.- Return type:
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.contentfragment joined in arrival order. The final chunk’susageis discarded — iterate the stream itself for that.- Return type:
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,StructOne 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.contentand isNoneor""on the role-only first chunk and the finish chunk.choicescan 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
Noneif the server did not report it on this chunk.object (str | None) – The object type (typically
"chat.completion.chunk"), orNone.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) –
ChatUsagetoken counts, populated on the final chunk andNoneon every earlier one.
- Parameters:
See also
ChatStreamChunk— the Pinecone-native chunk types, which deliver citations as objects you can render.- choices: list[ChatCompletionStreamChoice]¶
- class pinecone.models.assistant.streaming.ChatCompletionStreamChoice(*, index, delta, finish_reason=None)[source]¶
Bases:
StructDictMixin,StructA 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
choiceslist.delta (pinecone.models.assistant.streaming.ChatCompletionStreamDelta) – The
ChatCompletionStreamDeltafor this choice; the text is atdelta.content.finish_reason (str | None) –
Nonewhile 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 PythonNone, 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)
- delta: ChatCompletionStreamDelta¶
- class pinecone.models.assistant.streaming.ChatCompletionStreamDelta(*, role=None, content=None)[source]¶
Bases:
StructDictMixin,StructThe 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 carriesroleand nocontent, and the finish chunk carries neither.- Variables:
- Parameters:
- class pinecone.models.assistant.streaming.StreamContentDelta(*, content)[source]¶
Bases:
StructDictMixin,StructThe delta payload within a content chunk.
Reached as
chunk.deltaon aStreamContentChunk. This is where the response text lives in a Pinecone-native chat stream.
- class pinecone.models.assistant.streaming.StreamMessageStart(*, model, role, id=None, context_snippet_count=None, content_filter_results=None)[source]¶
Bases:
StructDictMixin,StructThe chunk that opens a chat stream, carrying no response text.
Arrives once, before any content. Carries nothing you have to render, but
context_snippet_countlets 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
Noneif the server did not report it here.context_snippet_count (int | None) – Number of retrieved context snippets that were provided to the model, or
Noneif the server did not report it.0means no relevant context was found for the query.content_filter_results (dict[str, Any] | None) – Safety classifications reported by the LLM provider, or
Nonewhen the provider returned none. Readspecfor the provider’s name andresultsfor a payload whose shape that provider defines.
- Parameters:
See also
ChatStreamChunk— the four chunk types and the loop that consumes them.
- class pinecone.models.assistant.streaming.StreamMessageEnd(*, id, usage=None, model=None, finish_reason=None, content_filter_results=None)[source]¶
Bases:
StructDictMixin,StructThe chunk that closes a chat stream, carrying usage and finish reason.
Arrives once, last, and carries no response text. Read
finish_reasonhere 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) –
ChatUsagetoken counts for the whole request, orNoneif the server did not report them.model (str | None) – Name of the model that generated the answer, or
Noneif 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 PythonNone, 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
Nonewhen the provider returned none. Readspecfor the provider’s name andresultsfor a payload whose shape that provider defines.
- Parameters:
See also
ChatStreamChunk— the four chunk types and the loop that consumes them.
- class pinecone.models.assistant.streaming.StreamContentChunk(*, id, delta, model=None, content_filter_results=None)[source]¶
Bases:
StructDictMixin,StructThe 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
StreamContentDeltaholding this fragment; the text is atdelta.content.model (str | None) – Name of the model that generated the answer, or
Noneif 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
Nonewhen the provider returned none. Readspecfor the provider’s name andresultsfor a payload whose shape that provider defines.
- Parameters:
See also
ChatStreamChunk— the four chunk types and the loop that consumes them.- delta: StreamContentDelta¶
- class pinecone.models.assistant.streaming.StreamCitationChunk(*, id, citation, model=None)[source]¶
Bases:
StructDictMixin,StructThe 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.positionis the character position in the response text the citation annotates, and each entry ofchunk.citation.referencesexposesreference.file(anAssistantFileModel, soreference.file.nameandreference.file.metadata),reference.pages, andreference.highlight. The highlight isNoneunless the chat request setinclude_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
ChatCitationholdingpositionandreferences.model (str | None) – Name of the model that generated the answer, or
Noneif the server did not repeat it on this chunk.
- Parameters:
id (str)
citation (ChatCitation)
model (str | None)
See also
ChatStreamChunk— the four chunk types and the loop that consumes them.- citation: ChatCitation¶
- class pinecone.models.assistant.streaming.AsyncChatStream(stream)[source]¶
Bases:
objectA Pinecone-native chat stream from
AsyncPinecone.Iterating it yields the same
ChatStreamChunkvariants asChatStream, so the branching contract is identical; only theasync for/awaitmechanics differ. The stream is single-pass: iterating,text(), andcollect()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
ChatStreamChunk— the four chunk types, and the loop to write when you need citations rather than text alone.AsyncChatCompletionStream— the same request in the OpenAI-compatible shape.
- 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.contentof eachStreamContentChunk, 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:
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
StreamContentChunkfragment joined in arrival order. Citations and token usage are discarded along with the other chunk types — iterate the stream itself for those.- Return type:
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:
objectAn OpenAI-compatible stream from
AsyncPinecone.Iterating it yields the same
ChatCompletionStreamChunkobjects asChatCompletionStream, with text atchunk.choices[0].delta.content; only theasync for/awaitmechanics differ. The stream is single-pass: iterating,text(), andcollect()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.contentof each chunk that has one, in arrival order. Chunks whose content isNoneor"", and chunks with an emptychoiceslist, are skipped, as isusageon the final chunk — iterate the stream itself for that.- Return type:
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.contentfragment joined in arrival order. The final chunk’susageis discarded — iterate the stream itself for that.- Return type:
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:
objectOne 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 aCondition, andCondition.to_dict()turns that into thefiltervalue.The two equality operators are Python’s own:
Field("genre") == "drama"builds$eqand!=builds$ne. Because==is overloaded to build a filter rather than answer a question, aFieldnever 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()andnot_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)
- gt(value)[source]¶
$gt— the field is greater than value (numeric only).- Raises:
TypeError – If value is not an
intorfloat. Aboolis rejected as well, though Python counts it as anint; compare a boolean field with==instead.- Parameters:
- Return type:
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
intorfloat. Aboolis rejected as well, though Python counts it as anint; compare a boolean field with==instead.- Parameters:
- Return type:
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
intorfloat. Aboolis rejected as well, though Python counts it as anint; compare a boolean field with==instead.- Parameters:
- Return type:
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
intorfloat. Aboolis rejected as well, though Python counts it as anint; compare a boolean field with==instead.- Parameters:
- Return type:
Examples
>>> from pinecone import Field >>> Field("duration_minutes").lte(120).to_dict() {'duration_minutes': {'$lte': 120}}
- 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']}}
- class pinecone.utils.filter_builder.Condition(filter_dict)[source]¶
Bases:
objectOne filter clause, or several combined.
Returned by every
Fieldoperator; you never construct one directly. Combine conditions with&for$andand|for$or, then callto_dict()to get the value to pass asfilter.Combining flattens same-operator nesting, so chaining three
&gives one$andof 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}}]}
- 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
Conditiondirectly with{}, which noFieldoperator does.- Return type:
Examples
>>> from pinecone import Field >>> Field("year").gte(2020).to_dict() {'year': {'$gte': 2020}}