AsyncPinecone¶
AsyncPinecone is the asynchronous control-plane client — use it inside an
async with block to manage indexes, collections, backups, and related resources.
Sub-clients for each resource type are accessed as properties (e.g.
pc.indexes, pc.collections) and are lazily initialised on first access.
from pinecone import AsyncPinecone
async with AsyncPinecone(api_key="your-api-key") as pc:
index = await pc.index("my-index")
async with index:
results = await index.query(
vector=[0.012, -0.087, 0.153],
top_k=10,
)
Note
AsyncPinecone.index() is a coroutine and must be awaited, where
Pinecone.index() is a plain call. Both resolve a
host the same way: an explicit host is used as-is, a name is served from the
host cache, and a name that misses the cache costs one describe request. Awaiting
is what makes that request non-blocking.
Pass host= when you already have it to skip the lookup entirely:
desc = await pc.indexes.describe("my-index")
idx = await pc.index(host=desc.host)
- class pinecone.async_client.pinecone.AsyncPinecone(api_key=None, *, host=None, additional_headers=None, source_tag=None, proxy_url=None, proxy_headers=None, ssl_ca_certs=None, ssl_verify=True, timeout=30.0, connection_pool_maxsize=0, retry_config=None)[source]¶
Bases:
objectEntry point to Pinecone’s control plane, over
asyncio.One client carries your API key, resolved host, and connection pool, so build it once — inside
async with, which closes it for you — and reuse it. Its namespace properties —indexes,collections,backups,backup_schedules,restore_jobs,inference, andassistants— create and inspect those resources. Vectors are read and written on the data plane instead, through the separate clientindex()hands back.Pineconeis the blocking twin, and Sync vs Async Clients compares the two. The one shape difference isindex(): here it is a coroutine you await, so the one describe request a cache-missing name costs does not block the event loop, and it takes nogrpc=argument, the gRPC transport being sync-only. Any call can raise the connection, timeout, and API errors catalogued in Error Handling, and everyRaises:section below names only what is specific to that method. Retries and Resilience covers what the client retries on your behalf and what retry_config changes.- Parameters:
api_key (str | None) – Your Pinecone API key.
None(default) readsPINECONE_API_KEYfrom the environment, which is how most deployments supply it.host (str | None) – Control-plane host, e.g.
"https://api.pinecone.io". A value with no scheme is read ashttps.None(default) readsPINECONE_CONTROLLER_HOST, then falls back to the public API. Point it elsewhere for a gateway, a private endpoint, or a local simulator.additional_headers (Mapping[str, str] | None) – Headers added to every control-plane request, e.g.
{"X-Request-Source": "nightly-reindex"}. When omitted, the client readsPINECONE_ADDITIONAL_HEADERSas a JSON object instead.source_tag (str | None) – Attribution tag appended to the User-Agent, e.g.
"acme-search-service". Lowercased, spaces become underscores, and anything outsidea-z,0-9,_and:is dropped.proxy_url (str | None) – Proxy for outgoing requests, e.g.
"http://proxy.corp.internal:3128".proxy_headers (Mapping[str, str] | None) – Not supported here: a non-empty mapping raises
NotImplementedErrorat construction. UsePineconewhen the proxy needs headers of its own.ssl_ca_certs (str | None) – Path to a CA bundle file, or to a directory of them, for a corporate root or a self-signed endpoint. It wins over
ssl_verify=False: pass both and verification stays on.ssl_verify (bool) – Whether to verify the server’s certificate.
True(default) is right everywhere but a throwaway test endpoint.timeout (float) – Deadline in seconds for a single HTTP attempt, not for the whole call — each retry gets its own. Defaults to
30.0.connection_pool_maxsize (int) – Ceiling on connections held open to the control plane.
0(default) leaves httpx’s own ceiling in place; raise it for a process issuing many concurrent control-plane calls.retry_config (RetryConfig | None) – Retry policy for control-plane requests.
None(default) uses the built-in policy, which suits most callers; see Retries and Resilience for the defaults, for how to switch retries off, and for why it does not reach data-plane REST.
- Raises:
PineconeValueError – If no API key is given and
PINECONE_API_KEYis unset, since nothing would authenticate the first request.NotImplementedError – If proxy_headers is non-empty.
FileNotFoundError – If
ssl_ca_certsnames a path that does not exist, raised on the first request rather than when the client is constructed, so a mistyped path cannot leave you silently verifying against the default trust store instead. A bundle that exists but cannot be parsed as a certificate raisesssl.SSLErrorat the same point.
Examples
Construct inside
async with, then reach the control plane through the namespace properties. Leavingapi_keyoff entirely reads it fromPINECONE_API_KEY:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: if not await pc.indexes.exists("product-search"): await pc.indexes.create( name="product-search", schema={"fields": {"embedding": { "type": "dense_vector", "dimension": 1536, "metric": "cosine"}}}, )
index()hands back a separate data-plane client scoped to one index, which is what reads and writes vectors. It manages its own connections, so it gets its ownasync withblock. A query vector has to be as wide as the index’s dense field — the three floats below stand in for a full 1536-dimensional embedding:async with AsyncPinecone(api_key="your-api-key") as pc: idx = await pc.index(name="product-search") async with idx: results = await idx.query( vector=[0.012, -0.087, 0.153], top_k=10, ) for match in results.matches: print(match.id, match.score)
- __init__(api_key=None, *, host=None, additional_headers=None, source_tag=None, proxy_url=None, proxy_headers=None, ssl_ca_certs=None, ssl_verify=True, timeout=30.0, connection_pool_maxsize=0, retry_config=None)[source]¶
- Parameters:
- Return type:
None
- property indexes: AsyncIndexes¶
Create, inspect, configure, and delete the project’s indexes.
- Returns:
The
AsyncIndexesnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: async for index in pc.indexes.list(): print(index.name, index.status.state)
- property collections: AsyncCollections¶
static snapshots of a pod-based index.
A collection is the pod-based snapshot format. The serverless equivalent is a backup, under
backups.- Returns:
The
AsyncCollectionsnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: for col in await pc.collections.list(): print(col.name, col.status)
- Type:
Create and inspect collections
- property assistants: AsyncAssistants¶
Create and manage Pinecone Assistants.
An assistant is a hosted, retrieval-augmented chat service: upload files to it and it answers questions grounded in their content, with no index or embedding pipeline of your own.
- Returns:
The
AsyncAssistantsnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: async for assistant in pc.assistants.list(): print(assistant.name, assistant.status)
- property assistant: _AsyncAssistantNamespaceProxy¶
Reach one assistant by name, or the whole namespace by attribute.
assistantsis the canonical namespace; this singular alias is not deprecated. It forwards every attribute there, and awaiting it with a name is shorthand fordescribe().- Returns:
A proxy that behaves like the
AsyncAssistantsnamespace for attribute access (pc.assistant.create(...)) and, when awaited with a name, returns that assistant’s details.
Examples
Awaiting the proxy with a name is shorthand for
describe():async with AsyncPinecone(api_key="your-api-key") as pc: bot = await pc.assistant("acme-support-bot") print(bot.status, bot.instructions)
Every other attribute forwards to the plural namespace, so
pc.assistant.createandpc.assistants.createare the same method reached two ways:async with AsyncPinecone(api_key="your-api-key") as pc: new_bot = await pc.assistant.create( name="acme-billing-bot", instructions="Help users with billing questions.", ) print(new_bot.status)
- property backups: AsyncBackups¶
Create, inspect, and delete backups of a serverless index.
Restoring one is not done from here: pass a
backup_idtocreate_index_from_backup(), which creates a new index from it. For pod-based indexes the snapshot format is a collection, undercollections.- Returns:
The
AsyncBackupsnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: for backup in await pc.backups.list(limit=100): print(backup.backup_id, backup.source_index_name, backup.status)
- property backup_schedules: AsyncBackupSchedules¶
Attach a recurring backup cadence to an index.
A schedule gives an index a daily, weekly, or monthly cadence, so Pinecone creates each backup for you rather than you triggering one every time.
- Returns:
The
AsyncBackupSchedulesnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: for schedule in await pc.backup_schedules.list( index_name="product-search" ): print(schedule.name, schedule.frequency, schedule.enabled)
- property restore_jobs: AsyncRestoreJobs¶
Track a restore that
create_index_from_backup()started.A restore job is the request itself, so it is what to follow when you passed
timeout=-1and the target index does not exist yet.- Returns:
The
AsyncRestoreJobsnamespace.
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: for job in await pc.restore_jobs.list(limit=10): print(job.restore_job_id, job.target_index_name, job.status)
- property inference: AsyncInference¶
Embed text or images, and rerank documents, on hosted models.
Reach for this when you want vectors or relevance scores without hosting a model yourself.
- Returns:
The
AsyncInferencenamespace.
Examples
multilingual-e5-largeis asymmetric, soinput_typetells it which side of a search the text belongs to —"passage"for text you intend to store,"query"for text you intend to search with:async with AsyncPinecone(api_key="your-api-key") as pc: embeddings = await pc.inference.embed( model="multilingual-e5-large", inputs=["Solar panels reduce energy costs and lower carbon emissions."], parameters={"input_type": "passage"}, ) print(len(embeddings.data))
- async create_index_from_backup(*, name, backup_id, deletion_protection=None, tags=None, read_capacity=None, timeout=None)[source]¶
Create a new index by restoring from a backup.
Polls until the restored index is ready, unless timeout is
-1. This is the only supported way to restore a backup:create_index()rejectssource_backup_id=with a message pointing here.- Parameters:
name (str) – Name for the new index.
backup_id (str) – Identifier of the backup to restore from. Obtain it from
AsyncBackups.createorAsyncBackups.list.deletion_protection (DeletionProtection | str | None) –
"enabled"or"disabled". Defaults to"disabled"server-side when omitted.tags (Mapping[str, str] | None) – Optional key-value tags for the new index. When omitted, the server copies the backup’s own tags.
read_capacity (dict[str, Any] | None) – Optional read capacity for the restored index —
{"mode": "OnDemand"}or{"mode": "Dedicated", "dedicated": {"node_type": ..., "scaling": "Manual", "manual": {"shards": ..., "replicas": ...}}}. Omitted entirely whenNone, leaving the server’s on-demand default in place. Serverless backups only; the server rejects a dedicated configuration too small to hold the backup.timeout (int | None) – Seconds to wait for readiness.
None(default) blocks up to 300 s.-1returns aCreateIndexFromBackupResponseimmediately (containsrestore_job_idandindex_id) without polling.
- Returns:
A
CreateIndexFromBackupResponsewhen timeout is-1(containsrestore_job_idandindex_id), or anIndexModeldescribing the restored index once it is ready.- Raises:
PineconeValueError – If name or backup_id is empty, or read_capacity is an empty dict.
PineconeTimeoutError – If the index is not ready within the timeout.
IndexInitFailedError – If the index enters
InitializationFailedstate.IndexTerminatedError – If the index enters
TerminatingorDisabledstate.NotFoundError – If backup_id does not match an existing backup.
ConflictError – If an index named name already exists.
ApiError – If the API returns another error response, for example if the backup is not yet complete.
- Return type:
Examples
The default form blocks until the restored index is ready and hands back the index itself, so the next call can use it:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.create_index_from_backup( name="product-search-restored", backup_id="bk-abc123", ) print(index.status.state)
timeout=-1returns as soon as the restore is accepted. What comes back is aCreateIndexFromBackupResponse, not an index — the index does not exist yet, so follow the restore throughpc.restore_jobsrather than treating the return value as one:async with AsyncPinecone(api_key="your-api-key") as pc: result = await pc.create_index_from_backup( name="product-search-restored", backup_id="bk-abc123", timeout=-1, ) job = await pc.restore_jobs.describe(job_id=result.restore_job_id) print(job.status)
A restore can land straight onto dedicated read nodes instead of the on-demand default:
async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.create_index_from_backup( name="product-search-restored", backup_id="bk-abc123", read_capacity={ "mode": "Dedicated", "dedicated": { "node_type": "t1", "scaling": "Manual", "manual": {"shards": 2, "replicas": 2}, }, }, ) print(index.status.state)
Changed in version 10.0: Added read_capacity, so a restore can land straight onto dedicated read nodes instead of defaulting to on-demand capacity.
- property config: PineconeConfig¶
Read back the settings this client resolved at construction.
- Returns:
PineconeConfigcarrying the resolved API key, host, timeout, and connection settings.
Examples
The values are post-resolution, with defaults and environment variables folded in, so this is where to confirm which host a client is actually pointed at:
async with AsyncPinecone(api_key="your-api-key") as pc: print(pc.config.host, pc.config.timeout)
- async index(name='', *, host='')[source]¶
Open an async data-plane client for one index, to read and write vectors.
A coroutine: awaiting it is what keeps the host lookup off the event loop. An explicit host is used as-is, a name is served from this client’s host cache, and a name that misses the cache costs one describe request. The sync twin,
Pinecone.index(), is a plain call, and is the only one of the two that can return a gRPC client.- Parameters:
- Returns:
An
AsyncIndex.- Raises:
PineconeValueError – If neither name nor host is given, or if name names an index that has no host yet — it is still initializing, so wait for its status to reach
Ready.NotFoundError – If name names no index in this project.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: idx = await pc.index(name="product-search") async with idx: print(await idx.describe_index_stats())
Passing the host skips the lookup, which saves a round trip when you already know it — from
AsyncIndexes.describe, or from your own config:async with AsyncPinecone(api_key="your-api-key") as pc: idx = await pc.index(host="product-search-abc123.svc.pinecone.io") async with idx: print(await idx.describe_index_stats())
Warning
The returned index manages its own HTTP client. Always use
async with idx:or callawait idx.close()when done — closing the parentAsyncPineconedoes not close index clients.See also
indexes— the control-plane namespace, for creating, listing, describing, configuring, and deleting indexes rather than reading from one.
- async close()[source]¶
Release this client’s control-plane connections.
Closes the control-plane connection pool, plus the
inferenceandassistantspools if those namespaces were used. Index clients fromindex()hold their own connections and are not closed here. Prefer the async context manager form,async with AsyncPinecone(...) as pc:, which calls this on the way out.Examples
The async context manager form closes the client on the way out, on an exception as well as on a normal exit:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: async for index in pc.indexes.list(): print(index.name)
Close it yourself when the client has to outlive a single block:
pc = AsyncPinecone(api_key="your-api-key") try: print(await pc.indexes.exists("product-search")) finally: await pc.close()
- Return type:
None
- async __aenter__()[source]¶
Enter the async context manager, returning this client.
- Returns:
This
AsyncPineconeinstance.- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: async for index in pc.indexes.list(): print(index.name)
AsyncIndexes¶
- class pinecone.async_client.indexes.AsyncIndexes(http, host_cache=None)[source]¶
Bases:
objectAsync control-plane operations for Pinecone indexes.
An index is the container your records live in: its searched fields are declared as a schema when you create it, and every query is aimed at one index. Reached as
pc.indexeson anAsyncPineconeclient; not constructed directly. MirrorsIndexesone-for-one.The backup methods here are scoped to a single index.
AsyncBackups(pc.backups) covers the project-wide backup listing plusdelete, which belong to no one index.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: names = [index.name async for index in pc.indexes.list()]
See also
AsyncPinecone.index(name)— the data-plane client for reads and writes against one index.Error Handling — the exceptions any method here can raise, and how to handle them.
Sync vs Async Clients — when to reach for this client over the synchronous one.
Changed in version 10.0: Graduated to the schema-based API.
create()takesschema=/deployment=instead ofspec=/dimension=/metric=/vector_type=;configure()nests pod scaling underdeployment=and droppedembed=;list()returns anAsyncPaginator; the index-scoped backup methods graduated from the preview namespace.- list(*, limit=None, pagination_token=None)[source]¶
List every index in the project.
The server returns them all in one page today, so the returned
AsyncPaginatoryields once and stops. It exposes the paginator interface anyway, so a call site written against it keeps working if that changes. Not a coroutine — iterate the result rather than awaiting the call.- Parameters:
limit (int | None) – Maximum number of indexes to yield. Must be a positive integer;
None(the default) yields every index.pagination_token (str | None) – Token from an earlier call, to resume where that call stopped;
Nonestarts from the beginning. See Pagination.
- Returns:
AsyncPaginatoroverIndexModelinstances.- Raises:
PineconeValueError – If limit is zero or negative.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: async for index in pc.indexes.list(): print(index.name, index.status.state)
Changed in version 10.0: Returns an
AsyncPaginatorinstead of anIndexList, and is no longer a coroutine — replace(await pc.indexes.list()).names()with[index.name async for index in pc.indexes.list()].
- async describe(name)[source]¶
Get detailed information about a named index.
Caches the index’s host, so a later
AsyncPinecone.index(name)call for the same name skips its own describe round trip.- Parameters:
name (str) – The name of the index to describe.
- Returns:
IndexModelwithname,host,schema,deployment,read_capacity,status,deletion_protection, andtags.- Raises:
PineconeValueError – If name is empty.
NotFoundError – If the index does not exist.
- Return type:
Examples
The returned host always carries the
https://scheme, even though the API reports it without one:async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.indexes.describe("my-index") print(index.host) print(list(index.schema.fields))
- async exists(name)[source]¶
Check whether a named index exists.
Calls
describe()internally and returnsFalseinstead of raising when the index isn’t found. Every other error propagates.- Parameters:
name (str) – The name of the index to check.
- Returns:
Trueif the index exists,Falseotherwise.- Raises:
PineconeValueError – If name is empty.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: if await pc.indexes.exists("my-index"): print("Index found")
Changed in version 10.0: An empty name now raises
PineconeValueErrorinstead of returningFalse.
- async delete(name, *, timeout=None)[source]¶
Delete an index by name.
Waits until the index is gone, polling every 5 seconds with no upper time bound unless you pass timeout.
- Parameters:
- Raises:
PineconeValueError – If name is empty.
NotFoundError – If the index does not exist.
ForbiddenError – If deletion protection is enabled — clear it with
configure()first.PineconeTimeoutError – If the index still exists after timeout seconds.
- Return type:
None
Examples
Delete an index and block until it is gone:
async with AsyncPinecone(api_key="your-api-key") as pc: await pc.indexes.delete("my-index")
Or bound the wait, so an index still present after a minute raises
PineconeTimeoutErrorinstead of polling forever:async with AsyncPinecone(api_key="your-api-key") as pc: await pc.indexes.delete("my-index", timeout=60)
Passing
timeout=-1returns as soon as the delete request is accepted, without polling at all — the index is still being torn down when the call returns.
- async create(*, schema=None, name=None, deployment=None, read_capacity=None, deletion_protection=None, tags=None, cmek_id=None, timeout=None, spec=None, dimension=None, metric=None, vector_type=None, **legacy_kwargs)[source]¶
Create a new index.
An index’s field layout is declared as a
schemaof named, typed fields. Every field in the schema must be one that gets searched —dense_vector,sparse_vector, orstringwithfull_text_searchenabled. Metadata-only fields aren’t declared here; they’re indexed automatically the first time they appear on an upserted record. The schema can’t change once the index exists, and the call waits until the index is ready unless you passtimeout=-1.- Parameters:
schema (dict[str, Any] | IndexSchema | None) –
The index’s field schema. Required unless the deprecated
dimension=(with optionalmetric=/vector_type=) is used instead — the two are mutually exclusive. A dict with a"fields"key mapping field names to typed configurations:{ "fields": { "embedding": {"type": "dense_vector", "dimension": 1536, "metric": "cosine"}, "body": {"type": "string", "full_text_search": {"language": "en"}}, } }
Also accepts the dict produced by
SchemaBuilderor anIndexSchema. A hybrid index has to declare itssparse_vectorfield here — see the note after the examples.full_text_search.languageaccepts a fixed set of language codes (or their English names, defaulten), butstop_words=Trueis not supported for every language — the server’s 400 names the unsupported language, by its English name rather than the code you sent.name (str | None) – Name for the index — 1-45 characters, lowercase alphanumerics and hyphens (e.g.
"movie-recommendations"). The server assigns a name when omitted.deployment (dict[str, Any] | None) – Deployment configuration, discriminated on
"deployment_type". For a managed index:{"deployment_type": "managed", "cloud": "aws", "region": "us-east-1"}. For a pod-based index,"deployment_type": "pod"plusenvironment,pod_type,replicas, andshards. Defaults to a managed index on AWSus-east-1when omitted. Mutually exclusive with the deprecatedspec=.read_capacity (dict[str, Any] | None) – Read capacity for a managed or BYOC index —
{"mode": "OnDemand"}or{"mode": "Dedicated", "dedicated": {"node_type": ..., "scaling": ..., "manual": {"replicas": ..., "shards": ...}}}.deletion_protection (str | None) –
"enabled"to blockdelete()on this index until it’s set back to"disabled"(the default).tags (Mapping[str, str] | None) – Key-value tags to attach, e.g.
{"env": "prod"}, up to 20 pairs. PassNone(the default) to attach none.cmek_id (str | None) – ID of a customer-managed encryption key to encrypt the index with, e.g.
"key-abc123".timeout (int | None) – How long to wait, in seconds, for the index to become ready before returning.
None(default) waits indefinitely;-1returns immediately without waiting.spec (Any) –
Deprecated. A
ServerlessSpec,PodSpec,ByocSpec, or the equivalent dict, translated intodeployment=(andread_capacity=when the spec carries one). Mutually exclusive withdeployment=. Usecreate_for_model()forIntegratedSpec.Deprecated since version 10.0: Pass
deployment=directly instead.dimension (int | None) –
Deprecated. Dense vector width for the legacy path, translated into a single-field
schema=. Required when creating a dense index this way.Deprecated since version 10.0: Declare a named field in
schema=instead.metric (Metric | str | None) –
Deprecated. Similarity metric for the legacy dense path —
"cosine"(default),"euclidean", or"dotproduct".Deprecated since version 10.0: Set
metricinside theschema=field declaration instead.vector_type (VectorType | str | None) –
Deprecated.
"dense"(default) or"sparse", for the legacy path.Deprecated since version 10.0: Declare a named
dense_vector/sparse_vectorfield inschema=instead.legacy_kwargs (Any)
- Returns:
IndexModeldescribing the created index — ready, unlesstimeout=-1was passed.- Raises:
PineconeValueError – If neither
schema=nordimension=is given, or mutually exclusive arguments (schema=with a legacy vector kwarg, ordeployment=withspec=) are combined.PineconeTypeError – If an unsupported legacy keyword (e.g.
pods=) orspec=IntegratedSpec(...)is passed.IndexInitFailedError – If the index fails to initialize.
PineconeTimeoutError – If the index isn’t ready before timeout elapses.
- Return type:
Examples
A dense index on the default deployment — managed, AWS
us-east-1:async with AsyncPinecone(api_key="your-api-key") as pc: await pc.indexes.create( name="movie-recommendations", schema={"fields": {"embedding": { "type": "dense_vector", "dimension": 1536, "metric": "cosine"}}}, )
A hybrid index, in a region of your choosing. The
sparse_vectorfield has to be declared here:configure()cannot add one later, so an index that needs sparse search and was created without it has to be recreated:async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.indexes.create( name="support-articles", schema={"fields": { "embedding": {"type": "dense_vector", "dimension": 1024, "metric": "cosine"}, "keywords": {"type": "sparse_vector"}, "body": {"type": "string", "full_text_search": {"language": "en"}}, }}, deployment={"deployment_type": "managed", "cloud": "aws", "region": "us-west-2"}, tags={"env": "prod"}, ) print(index.host)
Note
A hybrid index must declare its
sparse_vectorfield explicitly. A dense field withmetric="dotproduct"does not accept sparse values on its own: the create succeeds, and only the sparse upserts are refused later. The field cannot be added byconfigure(), so an index created without one has to be recreated. See Migrating to V10.See also
create_for_model()— creates an index with an integrated embedding model, so you upsert and query text instead of vectors.Changed in version 10.0:
spec=,dimension=,metric=, andvector_type=are deprecated, keyword-only sugar for the currentschema=/deployment=arguments.pods=,metadata_config=,source_collection=,source_backup_id=, andspec=IntegratedSpec(...)have no equivalent here; usecreate_for_model()for integrated embedding.
- async create_for_model(*, name, cloud, region, embed, deletion_protection=None, tags=None, schema=None, read_capacity=None, timeout=None)[source]¶
Create a serverless index with an integrated embedding model.
Pinecone embeds text written to the mapped field automatically at upsert time and embeds queries at read time using the same model. In the returned index, the embedding configuration surfaces as a
semantic_textfield inschema, named after thefield_maptext entry.- Parameters:
name (str) – Name for the index — 1-45 characters, lowercase alphanumerics and hyphens (e.g.
"semantic-search").cloud (str) – Public cloud provider —
"aws","gcp", or"azure".region (str) – Cloud region, e.g.
"us-east-1".embed (Mapping[str, Any] | Any) – Embedding configuration. A dict (or
EmbedConfig/IndexEmbed) with requiredmodelandfield_map(e.g.{"text": "chunk_text"}) and optionalmetric,dimension,read_parameters,write_parameters. The model cannot be changed after creation.deletion_protection (str | None) –
"enabled"to blockdelete()on this index until it’s set back to"disabled"(the default).tags (Mapping[str, str] | None) – Key-value tags to attach, e.g.
{"env": "prod"}, up to 20 pairs. PassNone(the default) to attach none.schema (dict[str, Any] | None) – Filterable metadata fields, e.g.
{"fields": {"genre": {"filterable": True}}}. A bare field map is wrapped in{"fields": ...}for you.read_capacity (dict[str, Any] | None) – Read capacity for the index — see
create().timeout (int | None) – How long to wait, in seconds, for the index to become ready before returning.
None(default) waits indefinitely;-1returns immediately without waiting.
- Returns:
IndexModeldescribing the created index — ready, unlesstimeout=-1was passed.- Raises:
PineconeValueError – If name, cloud, region, embed, tags, or deletion_protection fail client-side validation.
- Return type:
Examples
The
field_maptext entry names the record field Pinecone embeds, and that same name is what the field is called in the returned schema —chunk_textbelow:async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.indexes.create_for_model( name="semantic-search", cloud="aws", region="us-east-1", embed={"model": "multilingual-e5-large", "field_map": {"text": "chunk_text"}}, ) print(index.schema.fields["chunk_text"])
See also
create()— creates an index you supply the vectors for yourself, declaring them asdense_vector/sparse_vectorfields inschema=.
- async configure(name, *, deployment=None, schema=None, read_capacity=None, deletion_protection=None, tags=None, replicas=None, pod_type=None, serverless_read_capacity=None, **legacy_kwargs)[source]¶
Configure an existing index.
Only the fields you provide are updated; omitted parameters are left unchanged on the server. Read capacity and pod scaling apply asynchronously, so the call returns while the change is still in flight.
- Parameters:
name (str) – Name of the index to configure.
deployment (dict[str, Any] | None) – Pod-scaling updates for pod-based indexes —
{"replicas": int, "pod_type": str}(either or both). Must not include"deployment_type": deployment type, cloud/region, and environment cannot be changed after creation.schema (dict[str, Any] | IndexSchema | None) – Schema updates. Only
semantic_textfield parameters (read_parameters/write_parameters) are updatable server-side; see the note after the examples.read_capacity (dict[str, Any] | None) – Updated read capacity dict —
{"mode": "OnDemand"}or{"mode": "Dedicated", "dedicated": {...}}. Applies to managed and BYOC indexes.deletion_protection (str | None) –
"enabled"to blockdelete()on this index,"disabled"to allow it again.tags (Mapping[str, str] | None) – Tag updates, merged with existing tags on the server. Set a value to
""to delete that key; keys you do not mention are left unchanged. The tag cap is applied to the merged total rather than to this request, so adding tags to an index that already carries several can be rejected even though the request on its own is well within the cap. When the merge leaves no tags the index stores no tag map at all rather than an empty one.{}is rejected client-side.replicas (int | None) – Deprecated. Legacy pod-scaling replica count, translated into
deployment={"replicas": ...}. Mutually exclusive with deployment.pod_type (PodType | str | None) – Deprecated. Legacy pod type, translated into
deployment={"pod_type": ...}alongside replicas. Mutually exclusive with deployment.serverless_read_capacity (dict[str, Any] | None) – Deprecated. Legacy read-capacity keyword for managed indexes, translated straight into read_capacity. Mutually exclusive with read_capacity.
legacy_kwargs (Any)
- Returns:
IndexModelreflecting the updated index state. Readstatusfor how far an asynchronous change has got rather than assuming it landed.- Raises:
PineconeValueError – If name is empty, all kwargs are
None, any dict kwarg is empty, deployment includesdeployment_type, tags/deletion_protection are invalid, or deployment/read_capacity is combined with the deprecated keyword argument it translates to.PineconeTypeError – If
embed=orspec=is passed; neither has a translation here, and the message shows the equivalent current call where one exists.NotFoundError – If the index does not exist.
- Return type:
Examples
Scale a pod-based index. Pod scaling is applied in the background, so read
index.statuson the returned model to see how far the change has got rather than assuming it landed:async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.indexes.configure( "legacy-recommender", deployment={"replicas": 4, "pod_type": "p1.x2"} ) print(index.status.state)
Tag updates merge into the tags the index already carries. Given an index tagged
{"env": "staging", "team": "search"}, the call below setsenv, deletesteam— an empty value removes a key — and leaves every other tag as it was:async with AsyncPinecone(api_key="your-api-key") as pc: index = await pc.indexes.configure( "my-index", tags={"env": "prod", "team": ""} ) print(index.tags)
Note
Only
semantic_textfield parameters (read_parameters/write_parameters) can be updated throughschema=; other field types can’t be added, removed, or retyped after creation. Sincecreate()cannot declare asemantic_textfield directly, this only applies to indexes created withcreate_for_model().Changed in version 10.0: Before/after:
# 9.x await pc.indexes.configure("my-index", replicas=4, pod_type="p1.x2") # 10.x await pc.indexes.configure("my-index", deployment={"replicas": 4, "pod_type": "p1.x2"})
embed=is gone entirely, along with the convert-to-integrated flow it drove;replicas=/pod_type=/serverless_read_capacity=remain as deprecated keyword-only sugar fordeployment=/read_capacity=; and the method returns the updatedIndexModelinstead ofNone.Deprecated since version 10.0:
replicas=,pod_type=, andserverless_read_capacity=are translated intodeployment=/read_capacity=rather than sent as-is, and cannot be combined with the argument they translate to — passing both raisesPineconeValueError. New code should usedeployment=/read_capacity=directly.
- async create_backup(index_name, *, name=None, description=None)[source]¶
Create a backup of an index.
Index-scoped shortcut for
AsyncBackups.create, which does the same thing; the difference is that this one takes the index name positionally.- Parameters:
- Returns:
BackupModeldescribing the new backup.statusis typically"Initializing"right after creation; polldescribe_backup()until it reads"Ready"before restoring from it.- Raises:
PineconeValueError – If index_name is empty.
NotFoundError – If the index does not exist.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.indexes.create_backup( "my-index", name="nightly-20240115" ) print(backup.backup_id, backup.status)
Added in version 10.0: Graduated from
pc.preview.indexes.create_backup, now returning the single top-levelBackupModel.
- list_backups(index_name, *, limit=None, pagination_token=None, include_deleted=None)[source]¶
List the backups of one index, following pages as you iterate.
- Parameters:
index_name (str) – Name of the index whose backups to list.
limit (int | None) – Maximum number of backups to yield across all pages. Must be a positive integer.
Noneyields all backups. It also sets the requested page size, but only on a request that carries no pagination token: every later page is sized by the token, which already encodes it.pagination_token (str | None) – Token from an earlier call, to resume where that call stopped. limit still caps the total yield, but it is not sent alongside a token — see above. See Pagination.
include_deleted (bool | None) – When
True, include backups of every index that has ever used index_name, deleted ones included; those backups carry a non-Nonesource_index_deleted_at. WhenNone(the default) the parameter is omitted entirely and the server’s default (false) applies.
- Returns:
AsyncPaginatoroverBackupModelinstances. Iteration stops when the response carries no pagination envelope.- Raises:
PineconeValueError – If index_name is empty or limit is zero or negative.
NotFoundError – If index_name does not resolve to an active index — which is not the same as the name being unknown; see the note after the examples.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: async for backup in pc.indexes.list_backups("my-index"): print(backup.backup_id, backup.status)
Once every index that used a name has been deleted, that name’s backups come back only with
include_deleted=True— without it this raisesNotFoundError. They are the ones carrying asource_index_deleted_at:async with AsyncPinecone(api_key="your-api-key") as pc: backups = await pc.indexes.list_backups( "legacy-catalog", include_deleted=True ).to_list() print([b.backup_id for b in backups if b.source_index_deleted_at])
Important
NotFoundErrorhere does not necessarily mean index_name was never used. With include_deleted omitted orFalse, index_name must resolve to an active index: if every index that used the name has since been deleted, this raisesNotFoundErrorrather than returning an empty list. Retry withinclude_deleted=Trueto get those backups back; aNotFoundErrorthere means the name was never used in this project.See also
AsyncBackups.list— the project-wide listing, where the index name is an optional filter. It hands back one page for you to drive the token yourself, rather than a paginator that follows the pages for you.Added in version 10.0: Graduated from
pc.preview.indexes.list_backups, and gained include_deleted.
- async describe_backup(backup_id)[source]¶
Describe a backup by its ID.
Backups are identified independently of any index, so despite living on
indexesthis takes a backup ID rather than an index name.- Parameters:
backup_id (str) – Identifier of the backup to describe, as returned in
backup_idbycreate_backup().- Returns:
BackupModelwith the current state of the backup.- Raises:
PineconeValueError – If backup_id is empty.
NotFoundError – If the backup does not exist.
- Return type:
Examples
async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.indexes.describe_backup("bk-abc123") print(backup.status, backup.record_count)
See also
AsyncBackups.describe— the same lookup reached throughpc.backups, which takesbackup_idas a keyword argument rather than positionally.Added in version 10.0: Graduated from
pc.preview.indexes.describe_backup.
AsyncCollections¶
- class pinecone.async_client.collections.AsyncCollections(http)[source]¶
Bases:
objectAsync control-plane operations for Pinecone collections.
A collection is a static, point-in-time copy of a pod-based index’s vector data, held outside the index. Reach it as
pc.collections; not constructed directly —AsyncPineconebuilds and caches its own instance on first access.Collections are the snapshot mechanism for pod-based indexes;
AsyncBackupsis the one for serverless and BYOC indexes. The difference that decides which you want is restore: a backup can be restored into a new index withcreate_index_from_backup(), and a collection cannot be restored at all.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: for col in await pc.collections.list(): print(col.name, col.status)
See also
AsyncBackups— the equivalent for serverless and BYOC indexes, and the only snapshot you can restore.- Parameters:
http (AsyncHTTPClient)
- async create(*, name, source)[source]¶
Create a collection from an existing pod-based index.
A collection is a static copy of an index’s vector data, held outside the index as a snapshot of its contents at the moment it was taken. Only a pod-based index can be used as a source, and it must already be ready. The call returns as soon as creation starts — it does not wait for the collection to become ready.
- Parameters:
- Returns:
CollectionModelwhosestatusis"Initializing"until the snapshot has been built.- Raises:
PineconeValueError – If name or source is empty, or name doesn’t meet the naming rules above.
NotFoundError – If source does not name an index in this project.
- Return type:
Examples
The collection is still being built when the call returns, so its status is
"Initializing"rather than"Ready":col = await pc.collections.create( name="movie-embeddings-snapshot", source="movie-recommendations" ) print(col.status)
There is no
timeout=argument to wait on. Polldescribe()until the status leaves"Initializing", then readcol.statusto see where it settled:import asyncio while col.status == "Initializing": await asyncio.sleep(5) col = await pc.collections.describe(col.name)
Note
There is no path from a collection back to an index.
AsyncIndexes.create()rejectssource_collectionwith aPineconeTypeErrorin both spellings — as a top-level keyword argument, and nested in aPodSpecpassed to the deprecatedspec=argument. If you need a snapshot you can restore, back up a serverless index withAsyncBackups.create()and restore it withcreate_index_from_backup().See also
AsyncBackups.create()— the serverless equivalent, whose snapshot can be restored into a new index.
- async list()[source]¶
List every collection in the project.
There’s no filtering, sorting, or pagination — all collections come back at once.
- Returns:
CollectionList, which supports iteration,len(), index access, and anames()convenience method.- Return type:
Examples
collections = await pc.collections.list() print(collections.names()) for col in collections: print(col.name, col.status)
See also
AsyncBackups.list()— lists snapshots of serverless and BYOC indexes, and unlike this one is paginated.
- async describe(name)[source]¶
Get details about a collection.
- Parameters:
name (str) – Name of the collection to describe.
- Returns:
CollectionModelwithname,status,environment,size(bytes on disk),dimension, andvector_count.- Raises:
PineconeValueError – If name is empty.
NotFoundError – If the collection does not exist.
- Return type:
Examples
sizeis how much space the snapshot occupies, in bytes — not the dimension of its vectors. It,dimension, andvector_countareNoneuntil the collection finishes initializing:desc = await pc.collections.describe("movie-embeddings-snapshot") print(desc.status, desc.dimension, desc.vector_count, desc.size)
See also
AsyncBackups.describe()— the serverless equivalent, which reportsrecord_countandsize_bytesinstead.
- async delete(name)[source]¶
Delete a collection permanently.
Deletion is asynchronous: the call returns as soon as the request is accepted, and the collection can still show up in
list()for a short time afterwards. The source index can’t be deleted until the collection is really gone.- Parameters:
name (str) – Name of the collection to delete.
- Raises:
PineconeValueError – If name is empty.
NotFoundError – If the collection does not exist.
- Return type:
None
Examples
await pc.collections.delete("movie-embeddings-snapshot")
See also
AsyncBackups.delete()— the serverless equivalent, which takes abackup_idrather than a name.
AsyncBackups¶
- class pinecone.async_client.backups.AsyncBackups(http)[source]¶
Bases:
objectStored, point-in-time snapshots of a serverless or BYOC index.
A backup captures an index’s records and schema so that a new index can be created from it later with
create_index_from_backup(). Backups are identified by abackup_idof their own and outlive the index they were taken from. Reached aspc.backups; not constructed directly.Backups are the snapshot mechanism for serverless and BYOC indexes.
AsyncCollectionsis the pod-based equivalent, and the two do not interchange: a pod-based index is snapshotted into a collection, a serverless or BYOC index into a backup.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: page = await pc.backups.list(limit=100) print([b.backup_id for b in page])
See also
list_backups()— the index-scoped listing, which walks every page for you.Error Handling — the exceptions any of these methods can raise, and which ones are worth retrying.
- Parameters:
http (AsyncHTTPClient)
- async create(*, index_name, name=None, description=None)[source]¶
Create a backup of an existing index.
Only serverless and BYOC indexes can be backed up. The call returns as soon as the snapshot is initiated, not when it is ready.
- Parameters:
- Returns:
A
BackupModeldescribing the new backup. The call returns once the backup is initiated, sostatusis"Initializing"rather than"Ready"; polldescribe()to follow it.- Raises:
PineconeValueError – If index_name is empty.
ForbiddenError – If the organization’s plan does not include backups.
NotFoundError – If index_name does not resolve to an index in this project.
ApiError – If index_name names a pod-based index, which is snapshotted into a collection rather than a backup.
- Return type:
Examples
Poll
describe()until the status leaves"Initializing": a backup that fails settles on"Failed", so waiting for"Ready"specifically would never return.import asyncio from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.backups.create(index_name="product-search") print(backup.backup_id, backup.status) while backup.status == "Initializing": await asyncio.sleep(10) backup = await pc.backups.describe(backup_id=backup.backup_id) print(backup.status)
Give the backup a name and description so a later listing identifies it by more than its server-assigned
backup_id:async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.backups.create( index_name="product-search", name="daily-20240115", description="Scheduled daily backup before reindexing", )
See also
create()— a recurring cadence instead of this one-off snapshot.create_index_from_backup()— restoring a backup into a new index.
- async list(*, index_name=None, limit=None, pagination_token=None, include_deleted=None)[source]¶
List one page of backups.
When index_name is given, lists backups of that index only. Otherwise lists every backup in the project. One call returns one page: iterating the result walks that page and stops rather than following
paginationon your behalf. Drive the token yourself to walk the rest — see Pagination.- Parameters:
index_name (str | None) – Index name to scope the listing to, or
Nonefor every backup in the project.limit (int | None) – Maximum number of results per page. When
None, the parameter is omitted and the server applies its own default. Omitted too when pagination_token is given: the token already carries the page size it was minted with, and a different one sent alongside it would skip or repeat rows.pagination_token (str | None) – Offset token naming the next page, taken from
BackupList.pagination.next. Takes precedence over limit — see above.include_deleted (bool | None) – When
True, include backups of every index that has ever used index_name, deleted ones included. WhenNone(the default) the parameter is omitted entirely and the server’s default (false) applies. Only valid together with index_name.
- Returns:
A
BackupListsupporting iteration, len(), and index access.BackupList.paginationisNoneon the final page. Paging walks a live result set rather than a fixed snapshot, so de-duplicate bybackup_idrather than relying on page order.- Raises:
PineconeValueError – If include_deleted is given without index_name.
NotFoundError – If index_name does not resolve to an active index and include_deleted is not
True.
- Return type:
Examples
Passing index_name scopes the listing to one index:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: for backup in await pc.backups.list(index_name="product-search"): print(backup.name, backup.status)
Walk the project-wide listing by driving the token yourself, consuming each page before asking for the next one:
async with AsyncPinecone(api_key="your-api-key") as pc: page = await pc.backups.list(limit=100) backups = list(page) while page.pagination and page.pagination.next: page = await pc.backups.list( pagination_token=page.pagination.next ) backups.extend(page) print([b.backup_id for b in backups])
Backups outlive the index they were taken from, but an index-scoped listing resolves index_name against the active indexes first. Pass
include_deleted=Trueto reach the backups of an index you have already torn down:async with AsyncPinecone(api_key="your-api-key") as pc: orphaned = await pc.backups.list( index_name="legacy-catalog", include_deleted=True, ) print([b.backup_id for b in orphaned if b.source_index_deleted_at])
Note
If every index that ever used index_name has since been deleted, listing without include_deleted raises
NotFoundErrorrather than returning an empty list. Passinclude_deleted=Trueto see backups of deleted indexes too.See also
list_backups()— the same index-scoped listing as a paginator that walks every page, instead of one page plus a token.Changed in version 10.0: Added include_deleted.
BackupModelnow carriessource_index_deleted_atinstead ofdimension/metric.
- async describe(*, backup_id)[source]¶
Get the current state of one backup.
- Parameters:
backup_id (str) – The identifier of the backup to describe.
- Returns:
A
BackupModelwhosestatusis"Initializing","Ready", or"Failed", alongside thesource_index_nameit was taken from, the capturedschema, and therecord_countandsize_bytesof the snapshot.- Raises:
PineconeValueError – If backup_id is empty.
NotFoundError – If the backup does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.backups.describe(backup_id="bk-abc123") print(backup.status, backup.source_index_name)
See also
describe_backup()— the same call reached from theindexesnamespace, taking the backup id positionally.
- async get(*, backup_id)[source]¶
Get detailed information about a backup (alias for
describe()).- Parameters:
backup_id (str) – The identifier of the backup.
- Returns:
A
BackupModelwhosestatusis"Initializing","Ready", or"Failed", alongside thesource_index_nameit was taken from, the capturedschema, and therecord_countandsize_bytesof the snapshot.- Raises:
PineconeValueError – If backup_id is empty.
NotFoundError – If the backup does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: backup = await pc.backups.get(backup_id="bk-abc123") print(backup.status, backup.source_index_name)
- async delete(*, backup_id)[source]¶
Delete a backup.
- Parameters:
backup_id (str) – The identifier of the backup to delete.
- Raises:
PineconeValueError – If backup_id is empty.
NotFoundError – If the backup does not exist.
- Return type:
None
Examples
Deleting a backup discards the snapshot only. The index it was taken from is untouched, and other backups of that index remain:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: await pc.backups.delete(backup_id="bk-abc123")
AsyncBackupSchedules¶
- class pinecone.async_client.backup_schedules.AsyncBackupSchedules(http)[source]¶
Bases:
objectRecurring, time-based backups of a single index.
A schedule snapshots its index on a fixed cadence and retains each backup for a set number of days, so you do not have to call
create()on a timer of your own. Reached aspc.backup_schedules; not constructed directly.At most one schedule per index can be enabled at a time. The snapshots a schedule produces are ordinary backups: read one with
describe(), or list a schedule’s own runs withhistory().Note
Backups are a plan entitlement. A project without it gets a
ForbiddenErrorrather than aNotFoundErroreven for a schedule that does not exist, and on-demand backups are gated on the same entitlement, so they are not a fallback.Examples
Create a schedule, then follow the backups it produces. History rows appear as runs are planned, so a schedule created moments ago has little or nothing in it yet:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: schedule = await pc.backup_schedules.create( index_name="product-search", name="compliance-snapshots", frequency="daily", retention_days=90, ) print(schedule.schedule_id, schedule.next_scheduled_run) async for run in pc.backup_schedules.iter_history( schedule_id=schedule.schedule_id ): print(run.backup_id, run.status)
See also
Error Handling — the exceptions any of these methods can raise, and which ones are worth retrying.
- Parameters:
http (AsyncHTTPClient)
- async create(*, index_name, name, frequency, retention_days)[source]¶
Create a time-based backup schedule for an index.
A backup schedule runs automatically at a fixed cadence, producing a backup of the index on each run. There is no cron support here — choose one of the three fixed cadences below. For a single snapshot taken now, use
create()instead.- Parameters:
index_name (str) – Name of the index to attach the schedule to.
name (str) – Name for the schedule. Backups it produces are named
"{name}-{run timestamp}", so keep it short — see the note below.frequency (str) – Cadence for the schedule:
"daily","weekly", or"monthly".retention_days (int) – Number of days to retain each backup this schedule produces. Must be at least 1.
- Returns:
A
BackupScheduleModeldescribing the new schedule. It is created enabled, sonext_scheduled_runis already populated.- Raises:
PineconeValueError – If index_name or name is empty, if frequency is not a supported cadence, or if retention_days is less than 1.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the index does not exist.
ConflictError – If the index already has an enabled schedule — only one per index is allowed, so disable or delete the existing one first.
ApiError – If index_name names a pod-based index, which cannot be scheduled.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: schedule = await pc.backup_schedules.create( index_name="product-search", name="compliance-snapshots", frequency="daily", retention_days=90, ) print(schedule.schedule_id, schedule.next_scheduled_run)
The response spells the retention window
retention_expire_after_days, mirroring the request body’sretention.expire_after_days— the returned schedule has noretention_daysattribute.Important
Keep the schedule name short. Each run names its backup
"{name}-{run timestamp}", and the timestamp consumes a fixed share of the limit on resource names, so a long schedule name yields backup names past that limit. Neither the SDK nor the server rejects a long schedule name at create time; the cost surfaces later, at run time.
- async list(*, index_name, limit=None, pagination_token=None)[source]¶
List one page of an index’s backup schedules.
Schedules are always listed per index; there is no project-wide schedule listing. Disabled schedules are included, so a listing can hold several rows even though at most one may be enabled. One call returns one page — see Pagination.
- Parameters:
index_name (str) – Name of the index whose schedules to list.
limit (int | None) – Maximum results per page. Defaults to the server’s page size when
None. Ignored when a pagination token is given, since the token already carries the page size it was created with.pagination_token (str | None) – Token naming the next page, taken from the previous page’s
pagination.next. Takes precedence over limit — see above.
- Returns:
A
BackupScheduleListsupporting iteration,len(), and index access.BackupScheduleList.paginationisNoneon the final page.- Raises:
PineconeValueError – If index_name is empty or limit is zero or negative.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the index does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: schedules = await pc.backup_schedules.list(index_name="product-search") print(schedules.names()) print([s.schedule_id for s in schedules.enabled_schedules()])
names()andenabled_schedules()read the page in hand rather than the whole listing, so checkschedules.paginationbefore concluding that an index has no enabled schedule.See also
iter_schedules()— the same listing as a paginator that walks every page, instead of one page plus a token.
- iter_schedules(*, index_name, limit=None, pagination_token=None)[source]¶
Iterate every backup schedule on an index, fetching pages on demand.
The auto-paginating twin of
list(). Iteration stops when a response carries no pagination envelope or anullone.- Parameters:
- Returns:
A
AsyncPaginatoroverBackupScheduleModelinstances.- Raises:
PineconeValueError – If index_name is empty or limit is zero or negative. Raised as soon as you call this method, before the first page is fetched.
ForbiddenError – If the project’s plan does not include scheduled backups. Raised while iterating, when a page is fetched.
NotFoundError – If the index does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: async for s in pc.backup_schedules.iter_schedules( index_name="product-search" ): print(s.schedule_id, s.frequency, s.enabled)
See also
list()— one page plus its token, when you are driving pagination yourself.
- async describe(*, schedule_id)[source]¶
Get the current configuration of one backup schedule.
- Parameters:
schedule_id (str) – The identifier of the schedule to describe. This is the
schedule_idfromcreate()orlist(), not the index name.- Returns:
A
BackupScheduleModelcarrying the schedule’sfrequency, itsenabledflag, itsretention_expire_after_dayswindow, andnext_scheduled_run— which isNoneexactly when the schedule is disabled.- Raises:
PineconeValueError – If schedule_id is empty.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the schedule does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: schedule = await pc.backup_schedules.describe( schedule_id="e88f7273-42aa-47e9-af73-593827136867" ) print(schedule.enabled, schedule.next_scheduled_run)
- async get(*, schedule_id)[source]¶
Get detailed information about a schedule (alias for
describe()).- Parameters:
schedule_id (str) – The identifier of the schedule.
- Returns:
A
BackupScheduleModelcarrying the schedule’sfrequency, itsenabledflag, itsretention_expire_after_dayswindow, andnext_scheduled_run— which isNoneexactly when the schedule is disabled.- Raises:
PineconeValueError – If schedule_id is empty.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the schedule does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: schedule = await pc.backup_schedules.get( schedule_id="e88f7273-42aa-47e9-af73-593827136867" ) print(schedule.frequency)
- async update(*, schedule_id, frequency=None, retention_days=None, enabled=None)[source]¶
Update a backup schedule’s cadence, retention, or enabled state.
Only the arguments you pass are sent, so omitted fields are left unchanged rather than reset. The schedule’s
nameand its index cannot be changed – the API exposes no field for either.- Parameters:
schedule_id (str) – The identifier of the schedule to update.
frequency (str | None) – New cadence, one of
"daily","weekly","monthly".Noneleaves it unchanged.retention_days (int | None) – New retention window in days, at least 1.
Noneleaves it unchanged. Changing it also re-times the pending deletion of backups this schedule has already produced.enabled (bool | None) –
Falseto disable (clearingnext_scheduled_run),Trueto re-enable – see the warning above.Noneleaves it unchanged.
- Returns:
A
BackupScheduleModelwith the updated configuration. Afterenabled=Falseitsnext_scheduled_runisNone.- Raises:
PineconeValueError – If schedule_id is empty, if frequency is set to an unsupported cadence, or if retention_days is set to less than 1.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the schedule does not exist.
ConflictError – If
enabled=Trueand another schedule on the same index is already enabled.
- Return type:
Note
Calling this with none of frequency, retention_days, or enabled set still issues the
PATCH, with an empty body. It changes nothing server-side and hands back the schedule as it stands, but it is a request rather than a skipped one. Usedescribe()to re-read a schedule.Examples
Only the fields you name are sent. Moving this schedule to a weekly cadence with a shorter retention window leaves its
name, its index, and its enabled state exactly as they were:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: updated = await pc.backup_schedules.update( schedule_id="e88f7273-42aa-47e9-af73-593827136867", frequency="weekly", retention_days=30, ) print(updated.frequency, updated.retention_expire_after_days) print(updated.name, updated.enabled)
Pause the schedule instead, keeping the rest of its configuration:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: paused = await pc.backup_schedules.update( schedule_id="e88f7273-42aa-47e9-af73-593827136867", enabled=False, ) print(paused.frequency, paused.next_scheduled_run)
Warning
Passing
enabled=Trueon a disabled schedule immediately enqueues a backup run and recomputesnext_scheduled_runfrom the moment of the update rather than resuming the old slot, so a disable/re-enable cycle shifts the cadence rather than pausing it. Only one schedule per index can be enabled, so re-enabling raisesConflictErrorif another one already is. On an already-enabled schedule,enabled=Trueenqueues nothing.
- async delete(*, schedule_id)[source]¶
Permanently delete a backup schedule.
Backups the schedule already produced are not deleted; they age out on their own retention window. Deleting the schedule only stops future runs.
- Parameters:
schedule_id (str) – The identifier of the schedule to delete.
- Raises:
PineconeValueError – If schedule_id is empty.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the schedule does not exist – see the retry caveat above.
- Return type:
None
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: await pc.backup_schedules.delete( schedule_id="e88f7273-42aa-47e9-af73-593827136867" )
Important
This is not safe to retry blindly. A successful delete raises nothing, and a second attempt on the same
schedule_idraisesNotFoundError– so a retry after a dropped response is indistinguishable from deleting something that was never there. Treat aNotFoundErrorfollowing a delete attempt as success.
- async history(*, schedule_id, limit=None, pagination_token=None)[source]¶
List one page of the backups produced by a schedule.
Rows describe backup snapshots, not the schedule, and a row appears as soon as a run is planned – so the listing mixes runs that have already completed with ones that have not started. One call returns one page, and a frequent cadence with a long retention window has far more rows than one page holds — see Pagination.
- Parameters:
schedule_id (str) – The identifier of the schedule whose history to list.
limit (int | None) – Maximum results per page. Defaults to the server’s page size when
None. Ignored when a pagination token is given, since the token already carries the page size it was created with.pagination_token (str | None) – Token naming the next page, taken from the previous page’s
pagination.next. Takes precedence over limit — see above.
- Returns:
A
BackupScheduleHistoryListsupporting iteration,len(), and index access.BackupScheduleHistoryList.paginationisNoneon the final page.- Raises:
PineconeValueError – If schedule_id is empty or limit is zero or negative.
ForbiddenError – If the project’s plan does not include scheduled backups.
NotFoundError – If the schedule does not exist.
- Return type:
Examples
Walk the history a page at a time, narrowing each page to the runs that have not started yet.
scheduled()filters the page in hand, so it belongs inside the loop rather than after it:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: pagination_token = None while True: runs = await pc.backup_schedules.history( schedule_id="e88f7273-42aa-47e9-af73-593827136867", pagination_token=pagination_token, ) for run in runs.scheduled(): print(run.backup_id, run.scheduled_execution_at) pagination_token = runs.pagination.next if runs.pagination else None if pagination_token is None: break
See also
iter_history()— the same listing as a paginator that walks every page, instead of one page plus a token.
- iter_history(*, schedule_id, limit=None, pagination_token=None)[source]¶
Iterate every backup a schedule has produced, fetching pages on demand.
The auto-paginating twin of
history(). Iteration stops when a response carries no pagination envelope or anullone.- Parameters:
- Returns:
A
AsyncPaginatoroverBackupScheduleHistoryIteminstances.- Raises:
PineconeValueError – If schedule_id is empty or limit is zero or negative. Raised as soon as you call this method, before the first page is fetched.
ForbiddenError – If the project’s plan does not include scheduled backups. Raised while iterating, when a page is fetched.
NotFoundError – If the schedule does not exist.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: async for run in pc.backup_schedules.iter_history( schedule_id="e88f7273-42aa-47e9-af73-593827136867" ): print(run.backup_id, run.status, run.scheduled_execution_at)
See also
history()— one page plus its token, when you are driving pagination yourself.
AsyncRestoreJobs¶
- class pinecone.async_client.restore_jobs.AsyncRestoreJobs(http)[source]¶
Bases:
objectProgress reports for restores of a backup into a new index.
create_index_from_backup()hands back arestore_job_idand leaves the restore running in the background; this namespace is how you follow it to completion. Reached aspc.restore_jobs; not constructed directly.A restore job is not a backup:
AsyncBackupsmanages the snapshots themselves, while a job here is a read-only record of one attempt at turning a snapshot back into an index.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: job = await pc.restore_jobs.describe(job_id="rj-abc123") print(job.status, job.target_index_name)
See also
Error Handling — the exceptions any of these methods can raise, and which ones are worth retrying.
- Parameters:
http (AsyncHTTPClient)
- async list(*, limit=None, pagination_token=None)[source]¶
List one page of the project’s restore jobs.
One call returns one page:
RestoreJobListcarries apaginationtoken but never follows it, so iterating the return value sees at most one page. Drive the token yourself to walk the rest — see Pagination. The result is a best-effort sample rather than an inventory; the warning below says why that matters.- Parameters:
limit (int | None) – Maximum number of results per page. When
None, the parameter is omitted and the server applies its own default. Omitted too when pagination_token is given: the token already carries the page size it was minted with, and a different one sent alongside it would skip or repeat rows.pagination_token (str | None) – Offset token naming the next page, taken from
RestoreJobList.pagination.next. A malformed or truncated token is rejected with400(ApiError) rather than restarting the listing.
- Returns:
A
RestoreJobListsupporting iteration, len(), and index access. Itspaginationattribute isNoneon the final page.- Return type:
Examples
Walk every page the server will hand out. Because pages can overlap, the loop collects into a dict keyed by
restore_job_idrather than a list — that is the de-duplication the warning below calls for, and it costs nothing on a listing that happens not to repeat:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: by_id = {} page = await pc.restore_jobs.list(limit=100) while True: for job in page: by_id[job.restore_job_id] = job if not (page.pagination and page.pagination.next): break page = await pc.restore_jobs.list( pagination_token=page.pagination.next ) for job in by_id.values(): print(job.restore_job_id, job.target_index_name, job.status)
When one page is all you want:
async with AsyncPinecone(api_key="your-api-key") as pc: page = await pc.restore_jobs.list(limit=5) print(len(page))
Warning
This listing can silently drop restore jobs, stop paginating early, and repeat rows across pages. The token stream can end while restore jobs remain, and successive pages can overlap, so pages are neither exhaustive nor disjoint; a restore job whose target index has been deleted is dropped from the listing entirely. Treat the result as a best-effort sample rather than an inventory, never conclude a restore job does not exist from its absence here, and de-duplicate by
restore_job_idwhile walking pages.See also
describe()— the authoritative read for a single job, by id.
- async describe(*, job_id)[source]¶
Get the current state of one restore job.
- Parameters:
job_id (str) – The identifier of the restore job to describe.
- Returns:
A
RestoreJobModelnaming thebackup_idrestored and thetarget_index_nameit lands in.statusis one of"Pending","Completed","Failed", or"Cancelled": there is no in-progress state, so a restore that is actively running reports"Pending"and polling for a"Running"-style value never succeeds.percent_completeandcompleted_atare populated only oncestatusis"Completed", sopercent_completereports completion rather than progress and cannot drive a progress bar.- Raises:
PineconeValueError – If job_id is empty.
NotFoundError – If the API answers
404— which is not the same as “the restore job does not exist”; see the warning below.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: job = await pc.restore_jobs.describe(job_id="rj-abc123") print(job.status, job.target_index_name)
To wait for a restore, poll until
statusleaves"Pending"rather than waiting for it to reach a running state — there is no running state to reach. Bound the wait with a deadline so a job that never lands stops the loop instead of spinning forever; ten minutes below is illustrative, not a service guarantee:import asyncio import time async with AsyncPinecone(api_key="your-api-key") as pc: deadline = time.monotonic() + 600 job = await pc.restore_jobs.describe(job_id="rj-abc123") while job.status == "Pending" and time.monotonic() < deadline: await asyncio.sleep(5) job = await pc.restore_jobs.describe(job_id="rj-abc123") print(job.status, job.completed_at)
Warning
A ``404`` from this endpoint cannot be trusted to mean “no such restore job”. Any failure to read the restore-job store, an outage included, is answered with
404: what you see isNotFoundError, and what it actually means is “could not read this job”, not “this job does not exist”. Control flow keyed on it — giving up, deleting local state, reporting the job as gone — can each be wrong about what was really a transient failure, so treat it as possibly transient unless you have independent evidence the id is bad. A restore job whose target index has been deleted also answers404, under a different message, so do not match on message text either; such a job is dropped fromlist()entirely rather than reported.
AsyncInference¶
- class pinecone.async_client.inference.AsyncInference(config)[source]¶
Bases:
objectEmbedding and reranking against Pinecone’s hosted models.
Reached as
pc.inference. Call these when you want the vectors or the scores in your own hands — to store somewhere else, to embed a query yourself, or to rerank candidates that came from another system. If instead you want Pinecone to embed on your behalf, build an index withIntegratedSpecand useupsert_records(), which needs no explicit embed step. Not constructed directly.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: embeddings = await pc.inference.embed( model="multilingual-e5-large", inputs=["Vector databases index embeddings for similarity search."], parameters={"input_type": "passage"}, ) print(len(embeddings))
See also
Error Handling — the exceptions every method here can raise, and how to retry them.
- Parameters:
config (PineconeConfig)
- class EmbedModel(value)¶
-
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 RerankModel(value)¶
-
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'¶
- property model: AsyncModelResource¶
Model discovery for this namespace.
- Returns:
An
AsyncModelResourceexposinglist()andget().
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: info = await pc.inference.model.get("multilingual-e5-large") print(info.default_dimension) models = await pc.inference.model.list() print(models.names())
- async embed(model, inputs, parameters=None)[source]¶
Generate embeddings for the provided inputs.
Many models are asymmetric — they embed a stored passage and a search query differently — so where a model accepts
input_type, pass it in parameters, or the query and the corpus will not line up.- Parameters:
model (EmbedModel | str) – Embedding model name, e.g.
"multilingual-e5-large". AnEmbedModelmember is accepted too; calllist_models()withtype="embed"for the names currently available.inputs (str | Sequence[str] | Sequence[Mapping[str, Any]]) – The text to embed. Any sequence (list, tuple) of strings or mappings; a bare string is wrapped for you and still comes back as a one-item result rather than a lone embedding.
parameters (Mapping[str, Any] | None) – Model-specific parameters (e.g.,
{"input_type": "passage", "truncate": "END"}). Callget_model()and readsupported_parametersto discover the keys a given model accepts.
- Returns:
EmbeddingsList— one embedding per input, in input order. Iterating it (or indexing into it) yields the embeddings themselves, anddataholds the same list.vector_typesays which shape they are and so which fields they carry:DenseEmbeddinghasvalues, whileSparseEmbeddinghassparse_valuesandsparse_indices.modelnames the model that served the request, andusage.total_tokensthe tokens counted for it.- Raises:
PineconeValueError – If model is empty or inputs is empty.
PineconeTypeError – If inputs has an invalid type.
NotFoundError – If model is not available to this project — either no such model exists, or the project is not authorized to use it. The error does not distinguish the two cases.
- Return type:
Examples
Embed the text you intend to store.
input_type="passage"is the corpus side of a search:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: embeddings = await 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"}, ) print(len(embeddings), embeddings.vector_type)
Embed the search query with
input_type="query". The two are not interchangeable — a query embedded as a passage will not land where the model expects it:async with AsyncPinecone(api_key="your-api-key") as pc: query = await pc.inference.embed( model="multilingual-e5-large", inputs="How does reranking work?", parameters={"input_type": "query"}, ) print(len(query.data))
Note
To store these vectors in a Pinecone index, read the values off each embedding and pass them to
upsert():idx = await pc.index(name="product-search") values = embeddings.data[0].values await idx.upsert(vectors=[("doc-1", values)])
valuesexists only on the dense shape. A sparse embedding model returnsSparseEmbeddingobjects, which carrysparse_valuesandsparse_indicesand have novaluesfield — reading.valueson one hands back a dict-view method rather than a vector, and raises nothing to warn you. Branch onembeddings.vector_typewhen the model is not fixed in advance.See also
upsert_records()— on an index built withIntegratedSpec, Pinecone embeds the records for you and no call here is needed.
- async rerank(model, query, documents, rank_fields=['text'], return_documents=True, top_n=None, parameters=None)[source]¶
Rerank documents by relevance to a query.
- Parameters:
model (RerankModel | str) – Reranking model name, e.g.
"bge-reranker-v2-m3". ARerankModelmember is accepted too; calllist_models()withtype="rerank"for the names currently available.query (str) – The text the documents are scored against.
documents (Sequence[str] | Sequence[Mapping[str, Any]]) – Documents to rank. Any sequence (list, tuple) of strings or mappings. A bare string is wrapped as
{"text": ...}, which is what the default rank_fields scores on.rank_fields (Sequence[str]) – The document keys to score, e.g.
["summary"]when the text lives undersummary. Defaults to["text"].return_documents (bool) – Send each document back in its result. Leave it
Trueto read.document; set itFalsewhen you already hold the documents and want onlyindexandscore.top_n (int | None) – Keep only the n best-scoring documents.
None, the default, returns a result for every document.parameters (Mapping[str, Any] | None) – Model-specific parameters. Call
get_model()and readsupported_parametersto discover the keys a given model accepts.
- Returns:
RerankResultwhosedatais a list ofRankedDocumentordered by descendingscore. Each one carries theindexit held in documents and, unless return_documents isFalse, thedocumentitself.modelnames the model that served the request, andusage.rerank_unitsthe units counted for it.- Raises:
PineconeValueError – If model, query, or documents is empty, or top_n is less than 1.
PineconeTypeError – If documents has an invalid type.
NotFoundError – If model does not name a model the API serves. A typo in the model name surfaces here, so check this before assuming the request body was at fault.
ForbiddenError – If the project is not authorized to use model, including when model has been deprecated.
- Return type:
Examples
Rank a list of strings against the query.
result.datacomes back ordered by descending relevance, not by the order the documents were passed in, so read.indexto map a result back to its position in documents — the top hit below is the second document, so its.indexis1, not0:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: result = await 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, ) top = result.data[0] print(top.index, top.score, top.document["text"])
Pass mappings instead when you want your own identifiers back alongside the scores. Every key other than the ones named in rank_fields rides along untouched and comes back in
.document:async with AsyncPinecone(api_key="your-api-key") as pc: result = await pc.inference.rerank( model="bge-reranker-v2-m3", query="Tell me about tech companies", documents=[ {"id": "doc-1", "summary": "Apple is a fruit."}, {"id": "doc-2", "summary": "Acme Inc. revolutionized tech."}, ], rank_fields=["summary"], top_n=1, ) print(result.data[0].document["id"])
Note
The model you request may not be the model that serves the request — Pinecone may substitute a different one.
result.modelreports which one did, so read it there rather than assuming it echoes model.See also
search_records()— itsrerankargument reranks that search’s own hits in one round trip. Reach for the method here when the candidates came from somewhere else.
- async list_models(*, type=None, vector_type=None)[source]¶
List the inference models available to this project.
- Parameters:
- Returns:
ModelInfoList— a sequence ofModelInfosupporting iteration, indexing andlen(), plusnames()when you want the model identifiers alone.- Raises:
PineconeValueError – If type or vector_type is not one of the values above, or if vector_type is paired with
type="rerank"— the client rejects that pairing rather than ignoring it.- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: models = await pc.inference.list_models() print(models.names())
Narrow to the embedding models that produce sparse vectors:
async with AsyncPinecone(api_key="your-api-key") as pc: sparse = await pc.inference.list_models( type="embed", vector_type="sparse", ) print(sparse.names())
- async get_model(*, model=None, **kwargs)[source]¶
Describe one inference model.
- Parameters:
model (str) – The model name to look up, e.g.
"multilingual-e5-large". Calllist_models()for the names currently available.model_name (str) – Deprecated alias for model. Passing both raises
PineconeValueError.kwargs (str)
- Returns:
ModelInfowithsupported_parameters(the keys parameters accepts onembed()andrerank()for this model),type, and — for embedding models —vector_type,default_dimensionandsupported_dimensions.- Raises:
PineconeValueError – If model is empty, or if both model and model_name are given.
TypeError – If any keyword argument other than those above is passed.
NotFoundError – If no model of that name exists.
- Return type:
Examples
supported_parametersis whatembed()andrerank()point at for discovering the keys their parameters argument accepts, and each entry names the values it will take:from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: model_info = await pc.inference.get_model( model="multilingual-e5-large", ) print(model_info.type) for p in model_info.supported_parameters: print(p.parameter, p.allowed_values)
- class pinecone.async_client.inference.AsyncModelResource(inference)[source]¶
Bases:
objectDiscovery for the embedding and reranking models a project can use.
Reached as
pc.inference.model. Its two methods are the same operations asAsyncInference.list_models()andAsyncInference.get_model()— take whichever reads better at the call site. Not constructed directly.Examples
An unfiltered listing spans both model types — embedding models and reranking models alike:
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: models = await pc.inference.model.list() print(models.names())
- Parameters:
inference (AsyncInference)
- __init__(inference)[source]¶
- Parameters:
inference (AsyncInference)
- Return type:
None
- async list(*, type=None, vector_type=None)[source]¶
List the inference models available to this project.
Delegates to
AsyncInference.list_models().- Parameters:
- Returns:
ModelInfoList— a sequence ofModelInfosupporting iteration, indexing andlen(), plusnames()when you want the model identifiers alone.- Raises:
PineconeValueError – If type or vector_type is not one of the values above, or if vector_type is paired with
type="rerank"— the client rejects that pairing rather than ignoring it.- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: for info in await pc.inference.model.list(): print(info.model, info.type)
Narrow to the embedding models that produce sparse vectors:
async with AsyncPinecone(api_key="your-api-key") as pc: sparse = await pc.inference.model.list( type="embed", vector_type="sparse", ) print(sparse.names())
- async get(model=None, **kwargs)[source]¶
Describe one inference model.
Delegates to
AsyncInference.get_model().- Parameters:
- Returns:
ModelInfowithsupported_parameters(the keys this model accepts in a parameters argument),type, and — for embedding models —vector_type,default_dimensionandsupported_dimensions.- Raises:
PineconeValueError – If model is empty, or if both model and model_name are given.
TypeError – If any keyword argument other than those above is passed.
NotFoundError – If no model of that name exists.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: info = await pc.inference.model.get("multilingual-e5-large") print(info.type)
AsyncAssistants¶
- class pinecone.async_client.assistants.AsyncAssistants(config)[source]¶
Bases:
AsyncAssistantsLegacyNamespaceMixinAsync control-plane operations for Pinecone assistants.
A Pinecone assistant is a managed question-answering service grounded in documents you upload to it: create the assistant, upload files, then chat against them and get answers with citations back to the files that supported each claim.
Reached as
pc.assistantson anAsyncPineconeclient; not constructed directly. Unlike an index, which you query for records you then feed to your own model, an assistant does the retrieval and the generation for you.Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: async for assistant in pc.assistants.list(): print(assistant.name, assistant.status)
See also
Error Handling — the exceptions any of these methods can raise, and which ones are worth retrying.
- Parameters:
config (PineconeConfig)
- async close()[source]¶
Release the HTTP connections held by this namespace.
Call this when you’re done using
pc.assistantsto free pooled connections, including any opened for individual assistants.- Return type:
None
- async create(*, name=None, instructions=None, metadata=None, region='us', environment=None, timeout=None, **kwargs)[source]¶
Create a new Pinecone assistant.
A Pinecone assistant is a managed conversational AI service that answers questions grounded in documents you upload to it. This method creates the assistant and, by default, waits until it reaches
"Ready"status before returning.- Parameters:
name (str) – Name for the new assistant, e.g.
"docs-assistant". Must be unique within the project.instructions (str | None) – Guidance the assistant applies to every response, e.g.
"Always cite the source document.". Rejected if it exceeds the server’s size cap for the field.metadata (dict[str, Any] | None) – Optional metadata to attach to the assistant, e.g.
{"team": "docs"}.region (str) – Region to deploy the assistant in,
"us"or"eu". Defaults to"us". Cannot be changed afterwards — an assistant in the wrong region has to be recreated.environment (str | None) – Advanced override for select internal Pinecone deployments. Most users should leave this unset.
timeout (float | None) – Seconds to wait for the assistant to become ready. Use
None(default) to poll indefinitely,-1to return immediately without polling, or a non-negative value to poll with a deadline.**kwargs (Any) – Accepts the legacy alias
assistant_namefor name. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
AssistantModeldescribing the created assistant.- Raises:
PineconeValueError – If region is not
"us"or"eu".PineconeTimeoutError – If the assistant does not become ready before the deadline.
ApiError – If an assistant of this name already exists in the project, or the project has reached its assistant quota — delete one you no longer need before retrying.
- Return type:
Examples
from pinecone import AsyncPinecone async with AsyncPinecone(api_key="your-api-key") as pc: assistant = await pc.assistants.create(name="research-assistant") print(assistant.status)
Instructions, metadata and region are all optional.
createreturns once the assistant reaches"Ready", so the assistant below is usable as soon as the call returns:assistant = await pc.assistants.create( name="support-docs-assistant", instructions="Always cite the source document.", metadata={"team": "support", "cost_center": "R-4120"}, region="eu", )
- async describe(*, name=None, **kwargs)[source]¶
Get detailed information about a named assistant.
- Parameters:
name (str) – The name of the assistant to describe.
**kwargs (Any) – Accepts the legacy alias
assistant_namefor name. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
AssistantModelwith name, status, created_at, updated_at, metadata, instructions, and host.- Raises:
NotFoundError – If the assistant does not exist.
- Return type:
Examples
assistant = await pc.assistants.describe(name="research-assistant") print(assistant.status)
- list(*, limit=None, pagination_token=None)[source]¶
List assistants in the project with lazy pagination.
- Parameters:
- Returns:
AsyncPaginatoroverAssistantModelobjects. Supportsasync forloops,.to_list(),.pages(), andlimit.- Return type:
Examples
async for assistant in pc.assistants.list(): print(assistant.name, assistant.status)
The paginator fetches pages lazily as you iterate. Call
to_list()instead when you want every assistant materialized up front:all_assistants = await pc.assistants.list().to_list()
See also
list_page()— one page at a time, when you want to hold the continuation token yourself.Pagination — how the paginator and the continuation tokens work.
- async list_page(*, page_size=None, pagination_token=None, **kwargs)[source]¶
List one page of assistants with explicit pagination control.
Only the parameters that are explicitly provided are sent in the request. Omitted parameters are not included as query params.
- Parameters:
page_size (int | None) – Maximum number of assistants per page. Only sent when explicitly provided; omitted, the API chooses the page size. A value outside the range the API accepts comes back as an
ApiErrornaming the bound it broke.pagination_token (str | None) – Token from a previous response to fetch the next page.
**kwargs (Any) – Accepts the legacy alias
limitfor page_size. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
ListAssistantsResponsewith anassistantslist and an optionalnextcontinuation token.- Return type:
Examples
page = await pc.assistants.list_page(page_size=10) for assistant in page.assistants: print(assistant.name) if page.next: next_page = await pc.assistants.list_page( page_size=10, pagination_token=page.next, )
See also
Pagination — the continuation-token loop this method expects you to drive, and the paginator that drives it for you.
- async update(*, name=None, instructions=None, metadata=None, **kwargs)[source]¶
Update an existing Pinecone assistant.
Updates the specified assistant’s instructions and/or metadata. Metadata is fully replaced (not merged) when provided. At least one of instructions and metadata must be given.
Nonemeans “leave this field alone” — it is omitted from the patch body rather than sent as an explicit null, and the server has no way to clear a field from a null. To clear, send the empty value:instructions=""ormetadata={}.- Parameters:
name (str) – The name of the assistant to update.
instructions (str | None) – New instructions for the assistant. Pass an empty string to clear existing instructions.
metadata (dict[str, Any] | None) – New metadata dictionary. Fully replaces any existing metadata rather than merging. Pass an empty dict to clear existing metadata.
**kwargs (Any) – Accepts the legacy alias
assistant_namefor name. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
AssistantModeldescribing the updated assistant.- Raises:
PineconeValueError – If neither instructions nor metadata is provided.
NotFoundError – If the assistant does not exist.
- Return type:
Examples
Patch only the instructions.
metadatais left out of the request body entirely, so whatever metadata the assistant already carries survives untouched:assistant = await pc.assistants.update( name="research-assistant", instructions="Always cite the source document.", )
Passing
metadatareplaces the whole dictionary instead of merging into it. An assistant carrying{"team": "research", "cost_center": "R-4120"}is left with onlyteamafter the call below — and with its instructions unchanged, since they were not named:assistant = await pc.assistants.update( name="research-assistant", metadata={"team": "docs-platform"}, )
- async delete(*, name=None, timeout=None, **kwargs)[source]¶
Delete a Pinecone assistant by name.
By default, waits until the assistant is confirmed gone before returning.
If the assistant enters a terminal failure state while being deleted, waiting stops with
PineconeErrorinstead of polling indefinitely for a state that will never arrive.- Parameters:
name (str) – The name of the assistant to delete.
timeout (float | None) – Seconds to wait for the assistant to disappear. Use
None(default) to poll indefinitely. Use-1to return immediately without polling. Use a positive value to poll with a deadline. RaisesPineconeTimeoutErrorif the assistant is not gone before the deadline.**kwargs (Any) – Accepts the legacy alias
assistant_namefor name. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
None
- Raises:
PineconeError – If the assistant enters a terminal failure state (
"Failed","InitializationFailed") while being deleted.PineconeTimeoutError – If the assistant still exists after timeout seconds.
- Return type:
None
Examples
await pc.assistants.delete(name="research-assistant")
The call above blocks until the assistant is confirmed gone. Pass
timeout=-1to return as soon as the request is accepted — the assistant may still be terminating when this returns:await pc.assistants.delete(name="stale-prototype", timeout=-1)
- async describe_file(*, assistant_name, file_id, include_url=False)[source]¶
Get the status and metadata of a file uploaded to an assistant.
- Parameters:
- Returns:
AssistantFileModelwith file metadata and status.- Raises:
NotFoundError – If the file does not exist.
- Return type:
Examples
file = await pc.assistants.describe_file( assistant_name="research-assistant", file_id="file-abc123", ) print(file.status)
See also
list_files()— every file on the assistant. That listing drops a"ProcessingFailed"file once it is old enough; this method still returns it by id.
- async list_files_page(*, assistant_name, page_size=None, pagination_token=None, filter=None, **kwargs)[source]¶
List one page of files for an assistant with explicit pagination control.
- Parameters:
assistant_name (str) – Name of the assistant whose files to list.
page_size (int | None) – Maximum number of files in this page, sent as the
limitquery parameter. Only sent when explicitly provided; omitted, the API chooses the page size. A value outside the range the API accepts comes back as anApiErrornaming the bound it broke.pagination_token (str | None) – Token from a previous response to fetch the next page.
filter (dict[str, Any] | None) – Optional metadata filter expression. Serialized to a JSON string before being sent to the API.
**kwargs (Any) – Accepts the legacy alias
limitfor page_size. Passing both, or any other keyword, raisesPineconeValueError.
- Returns:
ListFilesResponsewith afileslist and an optionalnextcontinuation token.- Raises:
NotFoundError – If the assistant does not exist.
- Return type:
Examples
page = await pc.assistants.list_files_page( assistant_name="research-assistant", page_size=10, ) for f in page.files: print(f.name) if page.next: next_page = await pc.assistants.list_files_page( assistant_name="research-assistant", page_size=10, pagination_token=page.next, )
See also
Pagination — the continuation-token loop this method expects you to drive, and the paginator that drives it for you.
- list_files(*, assistant_name, filter=None, limit=None, pagination_token=None)[source]¶
List files for an assistant with lazy async pagination.
A
"ProcessingFailed"file drops out of this listing once itscreated_onpasses the listing’s age cutoff. It is not gone — it stays retrievable by id throughdescribe_file().- Parameters:
assistant_name (str) – Name of the assistant whose files to list.
filter (dict[str, Any] | None) – Optional metadata filter expression. Serialized to a JSON string before being sent to the API.
limit (int | None) – Maximum number of files to yield across all pages.
None(default) yields all files.pagination_token (str | None) – Token to resume pagination from a previous call.
- Returns:
AsyncPaginatoroverAssistantFileModelobjects. Supportsasync forloops,.to_list(),.pages(), andlimit.- Raises:
NotFoundError – If the assistant does not exist.
- Return type:
Examples
async for f in pc.assistants.list_files(assistant_name="research-assistant"): print(f.name, f.status)
The paginator fetches pages lazily as you iterate. Call
to_list()instead when you want every file materialized up front:paginator = pc.assistants.list_files(assistant_name="research-assistant") files = await paginator.to_list()
See also
describe_file()— one file by id, with no age filter: a"ProcessingFailed"file that has dropped out of this listing is still retrievable there.list_files_page()— one page at a time, when you want to hold the continuation token yourself.Pagination — how the paginator and the continuation tokens work.
- async upload_file(*, assistant_name, file_path=None, file_stream=None, file_name=None, metadata=None, multimodal=None, file_id=None, timeout=None)[source]¶
Upload a file to a Pinecone assistant.
Uploads a file from a local path or an in-memory byte stream, then waits until processing finishes before returning.
- Parameters:
assistant_name (str) – Name of the target assistant.
file_path (str | None) – Path to a local file to upload. Mutually exclusive with file_stream.
file_stream (IO[bytes] | None) – An open byte stream to upload. Mutually exclusive with file_path. Requires file_name.
file_name (str | None) – Filename to associate with file_stream. Required when file_stream is used, and must include a supported extension (
.txt,.pdf,.json,.md, or.docx), since the extension determines how the file is processed. Ignored when file_path is given, since its basename already supplies the extension.metadata (dict[str, Any] | None) – Optional metadata to attach to the file, e.g.
{"department": "research"}. Rejected if it exceeds the server’s metadata size cap, which is measured on the encoded bytes rather than on the number of keys.multimodal (bool | None) – Whether to enable multimodal processing for PDFs.
file_id (str | None) – Optional identifier for the uploaded file. When given, any existing file with that id is replaced. Otherwise the server assigns one.
timeout (float | None) – Seconds to wait for processing to complete.
None(default) polls indefinitely. Use-1to return immediately after upload with one describe call. RaisesPineconeTimeoutErrorif processing is not done before the deadline.
- Returns:
AssistantFileModeldescribing the uploaded file, once processing completes.- Raises:
PineconeValueError – If both or neither of file_path and file_stream are provided, if file_path does not exist, or if file_stream is used without a file_name carrying a file extension.
PineconeTimeoutError – If processing does not complete before timeout.
PineconeError – If processing fails.
- Return type:
Examples
Upload from a local path. The basename supplies the extension the server types the file by:
file = await pc.assistants.upload_file( assistant_name="research-assistant", file_path="/data/q3-revenue-review.pdf", ) print(file.id, file.status)
Or upload from an open byte stream instead.
file_pathandfile_streamare alternatives — pass exactly one — and a stream needsfile_nameto carry the extension a path would have supplied:with open("/data/q3-revenue-review.pdf", "rb") as handle: file = await pc.assistants.upload_file( assistant_name="research-assistant", file_stream=handle, file_name="q3-revenue-review.pdf", metadata={"department": "finance", "quarter": "2024-Q3"}, ) print(file.id, file.status)
- async delete_file(*, assistant_name, file_id, timeout=None)[source]¶
Delete a file from a Pinecone assistant.
Deletion can finish immediately or run as a pending operation, depending on the file’s state. When it is pending, this method polls until it finishes, unless you pass
timeout=-1.- Parameters:
assistant_name (str) – Name of the assistant that owns the file.
file_id (str) – Unique identifier of the file to delete.
timeout (float | None) – Seconds to wait for the deletion to finish. Use
None(default) to poll indefinitely. Use-1to return as soon as the request is accepted — the file may still exist when this returns. Use a positive value to poll with a deadline. RaisesPineconeTimeoutErrorif the deletion is not done before the deadline.
- Returns:
None- Raises:
NotFoundError – If file_id does not name a file on this assistant. Deleting an id that is already gone raises rather than returning silently.
PineconeError – If the deletion operation reports failure.
PineconeTimeoutError – If the deletion has not finished after timeout seconds.
- Return type:
None
Examples
await pc.assistants.delete_file( assistant_name="research-assistant", file_id="file-abc123", )
- async describe_operation(*, assistant_name, operation_id)[source]¶
Get the current status of a long-running assistant operation.
upload_file()anddelete_file()poll their own operation for you by default. Reach for this method when you called one of them withtimeout=-1and want to check on it later — for example, to find the file a fire-and-forget upload created, viaOperationModel.file_id.- Parameters:
assistant_name (str) – Name of the assistant that owns the operation.
operation_id (str) – Identifier of the operation to describe, as returned by
upload_file(),delete_file(), orlist_operations().
- Returns:
OperationModelwithstatus,operation_type,file_id,percent_complete,created_at,completed_on,ingestion_unitsanderror.statusis"Processing","Completed"or"Failed". Readerroronly whenstatusis"Failed": a retried operation keeps the previous attempt’s text, so a non-Noneerroris not by itself evidence of failure.- Raises:
NotFoundError – If the assistant or the operation does not exist. A finished operation stays describable until it ages out of the API’s retention window, and 404s from then on.
- Return type:
Examples
operation = await pc.assistants.describe_operation( assistant_name="research-assistant", operation_id="op-1234-abcd-5678", ) print(operation.status, operation.percent_complete)
See also
list_operations()— every operation on the assistant, when you did not keep the operation id.
- list_operations(*, assistant_name, operation_type=None, status=None, limit=None, pagination_token=None)[source]¶
List an assistant’s operations with lazy async pagination.
Covers operations that are still in progress as well as ones that finished — both successes and failures — until they age out of the API’s retention window.
- Parameters:
assistant_name (str) – Name of the assistant whose operations to list.
operation_type (str | None) – Restrict the listing to one kind of operation. One of
"upload_file","upsert_file","update_file_metadata"or"delete_file".status (str | None) – Restrict the listing to one status. One of
"Processing","Completed"or"Failed"(case-sensitive).limit (int | None) – Maximum number of operations to yield across all pages.
None(default) yields all of them.pagination_token (str | None) – Token to resume pagination from a previous call.
- Returns:
AsyncPaginatoroverOperationModelobjects. Supportsasync forloops,.to_list(),.pages(), andlimit.- Raises:
PineconeValueError – If operation_type or status is not one of the values above.
NotFoundError – If the assistant does not exist.
- Return type:
Examples
async for op in pc.assistants.list_operations(assistant_name="research-assistant"): print(op.operation_id, op.status, op.percent_complete)
Filter server-side to narrow the listing — here, uploads that have not finished yet:
pending = await pc.assistants.list_operations( assistant_name="research-assistant", operation_type="upload_file", status="Processing", ).to_list()
See also
describe_operation()— one operation by id, when you kept the id atimeout=-1call handed back.list_operations_page()— one page at a time, when you want to hold the continuation token yourself.Pagination — how the paginator and the continuation tokens work.
- async list_operations_page(*, assistant_name, operation_type=None, status=None, page_size=None, pagination_token=None)[source]¶
List one page of an assistant’s operations with explicit pagination control.
Only the parameters that are explicitly provided are sent in the request. Omitted parameters are not included as query params.
- Parameters:
assistant_name (str) – Name of the assistant whose operations to list.
operation_type (str | None) – Restrict the listing to one kind of operation. One of
"upload_file","upsert_file","update_file_metadata"or"delete_file".status (str | None) – Restrict the listing to one status. One of
"Processing","Completed"or"Failed"(case-sensitive).page_size (int | None) – Maximum number of operations in this page, sent as the
limitquery parameter. Only sent when explicitly provided; omitted, the API chooses the page size. A value outside the range the API accepts comes back as anApiErrornaming the bound it broke.pagination_token (str | None) – Token from a previous response to fetch the next page.
- Returns:
ListOperationsResponsewith anoperationslist and an optionalnextcontinuation token.- Raises:
PineconeValueError – If operation_type or status is not one of the values above.
NotFoundError – If the assistant does not exist.
- Return type:
Examples
page = await pc.assistants.list_operations_page( assistant_name="research-assistant", status="Failed", page_size=10, ) for op in page.operations: print(op.operation_id, op.error) if page.next: next_page = await pc.assistants.list_operations_page( assistant_name="research-assistant", status="Failed", page_size=10, pagination_token=page.next, )
See also
Pagination — the continuation-token loop this method expects you to drive, and the paginator that drives it for you.
- async context(*, assistant_name, query=None, messages=None, filter=None, top_k=None, snippet_size=None, multimodal=None, include_binary_content=None)[source]¶
Retrieve relevant context snippets from a Pinecone assistant.
Retrieves context snippets matching a text query or a conversation history, without generating a chat response. Provide exactly one of query or messages.
- Parameters:
assistant_name (str) – Name of the assistant to retrieve context from.
query (str | None) – Text query to use for context retrieval. Mutually exclusive with messages. An empty string is treated as not provided.
messages (Sequence[Message | Mapping[str, str]] | None) – Conversation messages to use for context retrieval. Mutually exclusive with query. An empty list is treated as not provided. Dicts are converted to
Messageobjects. Roles are case-sensitive"user"or"assistant"and content must be non-blank — seeMessage.filter (dict[str, Any] | None) – Metadata filter restricting which documents contribute context. Omitted from the request when
None.top_k (int | None) – Maximum number of context snippets to return. Omitted from the request when
None, in which case the API applies its own default.snippet_size (int | None) – Maximum snippet size in tokens. Omitted from the request when
None, in which case the API applies its own default.multimodal (bool | None) – Whether to include image-related context snippets. Omitted from the request when
None.include_binary_content (bool | None) – Whether image snippets include base64 image data. Only meaningful when multimodal is
True. Omitted from the request whenNone.
- Returns:
ContextResponsewithsnippets(each carryingcontent, a relevancescore, and areferencenaming the source file and, for paginated documents, the pages) andusage.- Raises:
PineconeValueError – If both or neither of query and messages are provided, or if top_k or snippet_size is negative.
- Return type:
Examples
response = await pc.assistants.context( assistant_name="research-assistant", query="What is Pinecone?", ) for snippet in response.snippets: print(snippet.content)
See also
chat()— a generated answer with structured citations, when you want Pinecone to do the generation as well.chat_completions()— a generated answer in OpenAI’s response shape.
- async chat(*, assistant_name, messages, model='gpt-4o', stream=False, temperature=None, filter=None, json_response=False, include_highlights=False, context_options=None, timeout=None)[source]¶
Chat with an assistant and receive citations in Pinecone-native format.
Citations come back as a structured list keyed to character positions in the answer, which is what separates this from
chat_completions(). The assistant answers only from the files you uploaded to it, so an assistant with nothing ingested yet errors rather than replying from general knowledge.- Parameters:
assistant_name (str) – Name of the assistant to chat with.
messages (list[Message | dict[str, str]]) – Conversation messages. Dicts are converted to
Messageobjects; role defaults to"user"when not present. Roles are case-sensitive"user"or"assistant"and content must be non-blank — seeMessage. Neither is checked client-side.model (str) – Name of the large language model that generates the answer. Defaults to
"gpt-4o". The models the API documents for this endpoint are"gpt-4o","gpt-4.1","gpt-5","o4-mini","claude-sonnet-4-5", and"gemini-2.5-pro". A name outside that list may be served by a successor model rather than rejected, so the response’smodelfield, not this argument, says which model answered. Not validated client-side; the API rejects an unrecognized name with an error enumerating what it accepts.stream (bool) – If
True, return anAsyncChatStream. Defaults toFalse.temperature (float | None) – Controls randomness. Lower values produce more deterministic responses. Omitted from request when
None.filter (dict[str, Any] | None) – Metadata filter restricting which documents are used as context. Omitted from request when
None.json_response (bool) – If
True, instruct the assistant to return a JSON response. Cannot be used with streaming.include_highlights (bool) – If
True, include highlight snippets from referenced documents in citations.context_options (ContextOptions | dict[str, Any] | None) – Options controlling context retrieval. Omitted from request when
None.timeout (float | None) – Per-call HTTP timeout in seconds, overriding the client-level default. On a streaming request this bounds the gap between chunks rather than the whole response (see below).
- Returns:
ChatResponsefor non-streaming requests, carryingmessage(the answer),citations(each with thepositionin the answer it supports and thereferencesbehind it),model(the model that answered),finish_reasonandusage. For streaming requests, anAsyncChatStream.- Raises:
PineconeValueError – If both
stream=Trueandjson_response=Trueare specified.ApiError – If the assistant has no file in
"Available"status yet — check withlist_files()before reading this as a transport failure.
- Return type:
Examples
import asyncio from pinecone import AsyncPinecone pc = AsyncPinecone(api_key="your-api-key") async def main() -> None: response = await pc.assistants.chat( assistant_name="research-assistant", messages=[{"content": "What is Pinecone?"}], ) print(response.message.content) for citation in response.citations: for reference in citation.references: print(citation.position, reference.file.name) asyncio.run(main())
Set
stream=Truefor anAsyncChatStreaminstead of a single response —text()yields content fragments as they arrive, skipping the start, citation and end chunks:async def stream_main() -> None: stream = await pc.assistants.chat( assistant_name="research-assistant", messages=[{"content": "What is Pinecone?"}], stream=True, ) async for text in stream.text(): print(text, end="", flush=True) asyncio.run(stream_main())
See also
chat_completions()— the same conversation in OpenAI’s response shape, with citations woven into the message text instead of returned as a structured list.context()— the retrieved snippets on their own, with no generated answer, when you want to prompt your own model.
Note
On a streaming request the timeout applies to the gap between chunks rather than the whole response, and the default is raised so a model that thinks for a while isn’t mistaken for a dead connection. Pass timeout to change it. A stream that exceeds its timeout raises
PineconeTimeoutErrorpartway through iteration, after earlier chunks have already been yielded.
- async chat_completions(*, assistant_name, messages, model='gpt-4o', stream=False, temperature=None, filter=None, timeout=None)[source]¶
Chat with an assistant using an OpenAI-compatible interface.
Returns responses in OpenAI chat completion format. Useful when you need inline citations or OpenAI-compatible responses. Has limited functionality compared to the standard
chat()interface — does not supportinclude_highlights,context_options, orjson_responseparameters.- Parameters:
assistant_name (str) – Name of the assistant to chat with.
messages (list[Message | dict[str, str]]) – Conversation messages. Dicts are converted to
Messageobjects; role defaults to"user"when not present. Roles are case-sensitive"user"or"assistant"and content must be non-blank — seeMessage. Neither is checked client-side.model (str) – Name of the large language model that generates the answer. Defaults to
"gpt-4o". The models the API documents for this endpoint are"gpt-4o","gpt-4.1","o4-mini","claude-sonnet-4-5", and"gemini-2.5-pro"— the same listchat()accepts, minus"gpt-5", which is documented only onchat(). A name outside that list may be served by a successor model rather than rejected, so the response’smodelfield, not this argument, says which model answered. Not validated client-side; the API rejects an unrecognized name with an error enumerating what it accepts.stream (bool) – If
True, return anAsyncChatCompletionStream. Defaults toFalse.temperature (float | None) – Controls randomness. Lower values produce more deterministic responses. Omitted from request when
None.filter (dict[str, Any] | None) – Metadata filter restricting which documents are used as context. Omitted from request when
None.timeout (float | None) – Per-call HTTP timeout in seconds, overriding the client-level default. On a streaming request this bounds the gap between chunks rather than the whole response (see below).
- Returns:
ChatCompletionResponsefor non-streaming requests, carryingchoices(readchoices[0].message.contentfor the answer, with citations woven into that text),model(the model that answered), andusage. For streaming requests, anAsyncChatCompletionStream.- Raises:
ApiError – If the assistant has no file in
"Available"status yet — check withlist_files()before reading this as a transport failure.- Return type:
Examples
import asyncio from pinecone import AsyncPinecone pc = AsyncPinecone(api_key="your-api-key") async def main() -> None: response = await pc.assistants.chat_completions( assistant_name="research-assistant", messages=[{"content": "Explain quantum entanglement briefly."}], ) print(response.choices[0].message.content) asyncio.run(main())
The response carries no separate
citationslist — the shape is OpenAI’s, so citations arrive inline in the message text. Setstream=Truefor anAsyncChatCompletionStream:async def stream_main() -> None: stream = await pc.assistants.chat_completions( assistant_name="research-assistant", messages=[{"content": "Explain quantum entanglement briefly."}], stream=True, ) async for chunk in stream: print(chunk) asyncio.run(stream_main())
See also
Note
On a streaming request the timeout applies to the gap between chunks rather than the whole response, and the default is raised so a model that pauses for longer while reasoning isn’t mistaken for a dead connection. Pass timeout to widen it further. A stream that exceeds its timeout raises
PineconeTimeoutErrorpartway through iteration, after earlier chunks have already been yielded.
- async evaluate_alignment(*, question, answer, ground_truth_answer)[source]¶
Evaluate answer alignment against a ground truth answer.
Measures the correctness and completeness of a generated answer with respect to a ground truth answer. Alignment is the harmonic mean of correctness (precision) and completeness (recall).
- Parameters:
- Returns:
AlignmentResultwith aggregate scores, per-fact entailment results, and token usage statistics.- Return type:
Examples
The answer below contradicts the ground truth on purpose, so the scores come back low and
result.factsrecords where the contradiction is:result = await pc.assistants.evaluate_alignment( question="What is the capital of Spain?", answer="Barcelona.", ground_truth_answer="Madrid.", ) print(result.scores.alignment) for fact in result.facts: print(fact.entailment, fact.fact)