Python SDK
A gRPC client for Python. It handles the token exchange, connection management and retries, so your code deals in collections and documents rather than in headers.
Every operation comes in two forms: CyrockDbClient blocks, and AsyncCyrockDbClient is awaited.
They are the same API - see Calling asynchronously.
Installing
The package is not on PyPI. Install it from the GitHub repository, pinned to a tag, which needs a GitHub account with access to that repository:
pip install "git+https://github.com/cyrock-ai/releases@db-v1.0.0#subdirectory=db-client-python"
Both names carry the db- prefix because that repository holds more than one product; the tag for a
given release is always db-v followed by the version. Pin a tag rather than a branch, so an install
is reproducible. Python 3.10 or later.
In a requirements file, the same line works with the tag pinned:
cyrock-db @ git+https://github.com/cyrock-ai/releases@db-v1.0.0#subdirectory=db-client-python
If your environment authenticates to GitHub over HTTPS with a token, the usual git credential
helper applies - pip shells out to git, so whatever works for git clone works here.
Protobuf compatibility
The generated gRPC modules are compiled against Protobuf 6.31.1 and grpcio 1.74.0, and both
rules run one way only: the runtime on your machine may be newer than the version the modules were
generated against, never older. An older one refuses to load them.
The Java SDK documents its floor as Protobuf 4.31.1. That is the same Protobuf release -
31.1 - not an older one. Protobuf versions its language runtimes on separate major lines:
protobuf-java 4.31.1 and the protobuf package on PyPI 6.31.1 ship from one release. Python has
no 4.31.1 at all, so do not copy the Java number into a requirements file - it cannot resolve.
|
Both SDKs are generated from the same release, so a Python and a JVM application talking to the same server are on the same wire format.
Connecting
from cyrock_db import CyrockDbClient
with CyrockDbClient(host="localhost", port=7290, api_key="your-api-key") as client:
...
The client is a context manager; close() works too if that suits your code better. One instance is
thread-safe and is meant to serve a whole application - constructing one per request wastes a
connection and a token exchange.
| Option | Default | Meaning |
|---|---|---|
|
|
Hostname or IP |
|
|
gRPC port. See below |
|
|
|
|
|
Exchanged for a short-lived token and attached to calls |
|
|
Custom credentials, such as mutual TLS. Wins over |
|
|
Seconds one request may take, retries included. Per request, not a budget for the client |
|
|
A |
|
|
Seconds idle before an HTTP/2 keep-alive ping |
|
|
Seconds to wait for that ping to be answered |
|
4 MiB |
Largest response the client will accept, in bytes |
Which port. The client sends both control-plane and data-plane calls over one connection, so the
endpoint has to front both. 7290 is the client gateway, which merges them, and is the default. A
bare data-server port such as 7292 is not a usable target: it serves the data plane only, so
the client connects successfully and then fails on the first control-plane call rather than at
connect time, which is a confusing way to find out.
Set call_timeout on anything long-lived. Without it, a request to a server that has stopped
answering but has not closed the connection waits forever, and your code has no way to notice.
Change streams are exempt from it - they are meant to stay open.
Retrying while the server comes back
A server that is restarting, being moved, or waking up after it was scaled to zero answers
UNAVAILABLE until it is back, and by default that reaches you as an UnavailableException. Give the
client a RetryPolicy and it retries those calls itself:
from cyrock_db.types import RetryPolicy
client = CyrockDbClient(api_key="your-api-key", call_timeout=30, retry_policy=RetryPolicy())
-
What is retried. Only calls that failed with
UNAVAILABLE, and by default only reads: the operations the protocol marks as free of side effects, plus the token exchange,recallandglobal_search, which touch state but are safe to repeat. A write that failed may still have been applied, its answer lost on the way back, so retrying it can apply it twice;RetryPolicy(retry_writes=True)opts into that where your writes tolerate it, such as upserts by key. CyQL statements count as writes, since one operation carries both. Change streams reconnect on their own and are not affected. -
One more
LOGINin the audit log, now and then. When the server completes a token exchange but its answer is lost, the retry exchanges again, and the audit log shows aLOGINevent for each exchange the server completed. The token from the lost answer never reaches the client and simply expires. A manual retry after a failed exchange leaves the same trace. -
How long it waits. Up to
max_attemptsattempts, five at most and by default. Before retry n the wait is bounded byinitial_backoff * backoff_multiplier ** (n - 1)seconds, capped atmax_backoff: by default half a second, doubling, capped at ten seconds. It is varied at random by up to a fifth either way, which keeps clients that lost the same server from all coming back at once. Backoffs shorter than 10 ms are refused. -
Set a
call_timeoutwith it. The timeout covers a call with all its retries, so it is what bounds how long a caller waits for a server that is not coming back.
Both CyrockDbClient and AsyncCyrockDbClient take it, and retry the same operations as the Java
client: both read which ones from the protocol.
Creating a collection
from cyrock_db.types import (
Cardinality, CollectionDefinition, MetadataFieldDefinition,
MetadataFieldType, VectorFieldDefinition,
)
collection = client.create_collection(project_id, CollectionDefinition(
name="documents",
vector_fields=(
VectorFieldDefinition(name="embedding", dimension=384),
),
metadata_fields=(
MetadataFieldDefinition(name="title", type=MetadataFieldType.STRING,
cardinality=Cardinality.HIGH, fulltext=True),
MetadataFieldDefinition(name="year", type=MetadataFieldType.INTEGER,
cardinality=Cardinality.LOW),
),
))
cardinality is required, and the choice is not cosmetic: it selects the index. HIGH builds a
binary index, suited to fields with many distinct values and to range and equality lookups. LOW
builds a bitmap, suited to fields with few distinct values - a status, a category, a year.
A vector field’s dimension is fixed once the collection exists. Adding a new vector field later
is allowed and takes effect immediately; changing an existing one’s dimension is not.
Documents
from cyrock_db.types import AUTO_ASSIGN_ID, Vector
document_id = client.upsert(
collection.id, AUTO_ASSIGN_ID,
{"embedding": Vector(embedding)},
{"title": "A paper about vectors", "year": 2026},
)
document = client.get_by_id(collection.id, document_id)
page = client.list(collection.id, offset=0, limit=100)
client.delete(collection.id, document_id)
AUTO_ASSIGN_ID asks the store to choose an id. Note that 0 is a real id - documents are numbered
from zero - so do not use it to mean "assign me one".
For repeatable ingest, address documents by a key of your own instead. Re-sending the same key updates rather than duplicating, and the result says which happened:
result = client.upsert_document(collection.id, "paper-2026-001",
{"embedding": Vector(embedding)},
{"title": "A paper about vectors", "year": 2026})
result.created # True the first time, False on every re-ingest
Numbers keep their type through storage. A Python int beyond 2^53 - past what a float can hold
exactly - comes back as the integer you stored, not a rounded one.
Searching
from cyrock_db.types import SearchRequest
matches = client.search(collection.id, SearchRequest(
vector_field="embedding", vector=query_embedding, max_results=10,
))
for match in matches:
print(match.score, match.document.metadata["title"])
Narrow a search with a CyQL filter, and bind every caller-supplied value as a $name in
filter_parameters rather than formatting it into the string. A formatted value can break out of its
quotes and rewrite the predicate; a bound one is always compared as a literal:
matches = client.search(collection.id, SearchRequest(
vector_field="embedding", vector=query_embedding, max_results=10,
filter="visibility = $v AND owner = $owner",
filter_parameters={"v": "public", "owner": caller_id},
))
Every request type that takes a filter takes filter_parameters too, and ChangeFilter has
metadata_predicate_parameters for its metadata_predicate.
Combine vector similarity with full-text scoring when a query has both a meaning and some keywords:
from cyrock_db.types import FusionStrategy, HybridSearchRequest, TextQuery, VectorQuery
matches = client.hybrid_search(collection.id, HybridSearchRequest(
vector_queries=(VectorQuery("embedding", query_embedding, 1.0),),
text_queries=(TextQuery("title", "machine learning", 1.0),),
max_results=10,
fusion=FusionStrategy.RRF,
))
multi_search does the same across several vector fields, which is how a multi-modal item with a
text embedding and an image embedding is searched.
Vectors and fusion weights travel as 32-bit floats, while a Python float is a double. A weight of
0.7 arrives as 0.699999988, and a vector read back is the 32-bit rounding of what you sent. Worth
knowing before comparing a returned vector against the original.
Running CyQL
from cyrock_db.types import QueryParameters
result = client.query(graph.id, """
MATCH (n:Concept) SIMILAR TO $v ON embedding TOP 5
RETURN n, score(n) AS s ORDER BY s DESC
""", QueryParameters.builder().vector("v", query_embedding).build())
for row in result.rows:
print(row["s"], row["n"])
execute decides where a statement belongs and sends it there - schema statements such as
CREATE GRAPH go to the control plane, everything else to the resource:
client.execute(project_id, graph.id, "MATCH (n:Concept) RETURN n")
It takes both ids because it cannot know in advance which one the statement needs; pass None for
whichever your statement cannot use.
Unlike the Java SDK, this client does not parse a statement before sending it, so a syntax error is reported by the server rather than refused locally. The message is the server’s own.
Calling asynchronously
AsyncCyrockDbClient offers every operation the blocking client has, awaited:
import asyncio
from cyrock_db.aio import AsyncCyrockDbClient
async def main():
async with AsyncCyrockDbClient(api_key="your-api-key") as client:
results = await asyncio.gather(*(
client.search(collection_id, SearchRequest("embedding", query, 10))
for query in queries
))
asyncio.run(main())
It does not make a single call faster. It buys concurrency without threads: the blocking client parks a thread for every round trip, so fifty searches at once wants fifty threads doing nothing but waiting. Here they are in flight on one connection and none waits.
Where it helps, and where it does not
Reads and searches gain: the server takes a read lock per store, so they run in parallel. Writes to one collection are serialized behind its write lease regardless of the client, so fanning writes out mostly moves the queue from your side to the server’s. Fan out reads; fan out writes only when they are independent and across different collections.
Ordering
Two coroutines started together have no order between them. A read fired alongside its own write may not see it. Await the first before starting the second when the order is the point:
document_id = await client.upsert(collection_id, AUTO_ASSIGN_ID, vectors, metadata)
document = await client.get_by_id(collection_id, document_id)
Concurrent writes to one collection apply in arrival order, not submission order.
Two differences from the blocking client
The asynchronous client is constructed and closed on its own - there is no method on the blocking client that hands you one. The two hold separate connections, which is a consequence of how asyncio gRPC works rather than a choice.
Change streams are the one operation whose shape differs; see below.
Transactions
Both transaction surfaces are all-or-nothing: every operation commits, or none does.
from cyrock_db.types import RemoveDocumentOp, UpsertDocumentOp
result = client.execute_document_transaction(collection.id, [
UpsertDocumentOp(id=AUTO_ASSIGN_ID, vectors={"embedding": Vector(first)}, metadata=meta),
UpsertDocumentOp(id=AUTO_ASSIGN_ID, vectors={"embedding": Vector(second)}, metadata=meta),
RemoveDocumentOp(document_id=old_id),
])
result.results[0].generated_id # the id the first upsert was assigned
result.results[2].generated_id # None: a remove generates nothing
execute_transaction is the graph equivalent, over AddNodeOp, AddEdgeOp, UpsertNodeOp,
UpdateNodeOp and the rest. A failing operation fails the whole call with an exception and rolls
everything back, so a returned result always describes a committed transaction. Only operations that
create or upsert carry a generated_id; removes and updates report None, never 0, since 0 is
the id of the first entity.
Removing something that does not exist is not an error: the transaction commits, which keeps a cleanup transaction re-runnable.
A transaction is one call: the whole operation list goes to the server at once and commits as one unit. There is no open-then-commit session spanning several calls, and a transaction covers one collection or one graph.
A node and its edges in one transaction
A new node’s id is assigned only when the transaction runs, so an edge to it cannot name it by id. Each
endpoint of an AddEdgeOp is therefore either an existing node, EndpointNodeId(node_id) or just the
int id, or the node an earlier operation of the batch creates, EndpointOperationIndex(index), where
index is that AddNodeOp or `UpsertNodeOp’s position in the list.
from cyrock_db.types import AddEdgeOp, AddNodeOp, EndpointOperationIndex
result = client.execute_transaction(graph.id, [
AddNodeOp(labels=["Person"], metadata={"name": "Ada"}), # 0
AddNodeOp(labels=["Person"], metadata={"name": "Bob"}), # 1
AddEdgeOp(EndpointOperationIndex(0), EndpointOperationIndex(1), "KNOWS", 0.9),
AddEdgeOp(EndpointOperationIndex(0), company_id, "WORKS_AT"),
])
ada_id = result.results[0].generated_id
All four apply or none do: if the company node does not exist, Ada and Bob are rolled back with the
edges. An index must point back at an earlier AddNodeOp or UpsertNodeOp; one that points forward, at
itself or at any other operation fails the transaction as invalid.
The same works as a single CyQL statement, which is often shorter:
INSERT (a:Person {name: 'Ada'})-[:KNOWS]→(b:Person {name: 'Bob'}) through execute_statement.
Edges to nodes known by key
When your nodes carry an external key of your own (upsert_node or UpsertNodeOp), an endpoint can name
the node by that key instead of its id: EndpointKey("person:42"). The server resolves the key when the
edge’s operation runs, so you skip reading the ids first, and the key also finds a node an earlier
UpsertNodeOp of the same batch created:
from cyrock_db.types import AddEdgeOp, EndpointKey, EndpointOperationIndex, UpsertNodeOp
client.execute_transaction(graph.id, [
UpsertNodeOp(external_key="post:7", labels=["Post"], metadata={"title": "Hello"}), # 0
AddEdgeOp(EndpointOperationIndex(0), EndpointKey("person:42"), "HAS_CREATOR"),
AddEdgeOp(EndpointKey("forum:3"), EndpointKey("post:7"), "CONTAINER_OF"),
])
A key no node holds fails the whole transaction as not found, naming the key. On a branch, which cannot upsert by key yet, a key finds only the keyed nodes the branch sees from its parent.
Errors
Every exception extends CyrockDbClientException, which carries an HTTP status code.
| Exception | Status | Raised when |
|---|---|---|
|
404 |
The resource does not exist |
|
403 |
Your permissions do not cover the request |
|
401 |
Not authenticated |
|
503 |
Server unreachable or not accepting requests |
|
504 |
The call did not finish within its deadline |
|
409 |
The write committed and is visible, but the durability flush did not confirm |
UnavailableException and DeadlineExceededException share a base, RetryableException. Catch that
rather than comparing numbers - the arithmetic is easy to get wrong in the direction that never retries.
Or let the client resend for you, see
Retrying while the server comes back; with a retry policy, an UnavailableException from a read
means its retries ran out:
from cyrock_db import CyrockDbClientException, RetryableException
try:
matches = client.search(collection.id, request)
except RetryableException:
... # worth another attempt
except CyrockDbClientException as error:
print(error.status_code, error)
429 is deliberately not retryable: it is the server asking for less load, not for the same request
again. Nor is DurabilityNotConfirmedException - that write already stands, and sending it again
would apply it twice. Verify, alert, or change the durability mode instead.
Graphs
from cyrock_db.types import AddEdgeRequest, GraphDefinition, ListNodesRequest
graph = client.create_graph(project_id, GraphDefinition(
name="concepts",
node_vector_fields=(VectorFieldDefinition(name="embedding", dimension=384),),
))
first = client.add_node(graph.id, ["Concept"], {"embedding": Vector(a)}, {"title": "vectors"})
second = client.add_node(graph.id, ["Concept"], {"embedding": Vector(b)}, {"title": "indexes"})
client.add_edge(graph.id, AddEdgeRequest(first, second, "RELATES_TO", weight=0.9))
nodes = client.list_nodes(graph.id, ListNodesRequest(labels=["Concept"], limit=100))
get_node and remove_node take either an id or a key of your own, and do the right thing with
each. To read many nodes by your own keys, get_nodes_by_keys(graph.id, keys) resolves the whole set in
one call; a key no node holds is left out, and each node carries its external_key to map the result back.
Vectors are opt-in on reads. list_nodes, neighbors, get_nodes and get_nodes_by_keys leave them
out unless asked, because collecting them is the expensive part of building a node - at 384 dimensions with
200 neighbours it is around 77,000 floats that most readers never look at:
client.list_nodes(graph.id, ListNodesRequest(limit=100, include_vectors=True))
Collection searches work the same way: SearchRequest, MultiVectorSearchRequest and
HybridSearchRequest return matches without vectors unless include_vectors=True is set.
Sampling. A page is otherwise the first n nodes by id, and id order is insertion order - so a
graph written one label at a time hands back a page whose nodes all share a label. Pass a
sample_seed for a representative slice. Seeded rather than random, so a reload shows the same nodes
instead of reshuffling under whoever is reading.
Beyond this the graph surface covers traversal (neighbors, traverse, reasoning_chain),
retrieval-augmented reads (context_window, the community layer, global_search), agentic memory
(observe, recall, decay) and branching (fork_graph, merge_graph). traverse and context_window
return nodes without their vectors unless the request sets include_vectors=True, and a TraverseRequest
takes a limit on the nodes it returns, so the server stops walking once it has them.
Edge metadata is opt-in too. neighbors_graph, context_window_graph, reasoning_chain_graph,
recall_graph and induced_subgraph return each edge with its id, type, endpoints and weight, an empty
metadata and a created_at of 0, unless the request sets include_edge_metadata=True (a keyword argument
of induced_subgraph). Without it the server loads no edge, which on a hub is most of the cost of the read:
client.neighbors_graph(graph.id, NeighborsRequest(node_id, Direction.INCOMING, include_edge_metadata=True))
Change streams
watch_graph and watch_collection follow changes as they happen. Delivery is at-least-once with a
resumable cursor: record the LSN you last processed, and de-duplicate on it.
from cyrock_db.types import WatchOptions
def on_change(event):
print(event.op, event.entity_id, event.lsn)
with client.watch_graph(graph.id, WatchOptions.with_snapshot(), on_change) as stream:
... # events arrive on a background thread
checkpoint(stream.last_lsn)
Start from now, from a snapshot of current state, or from a checkpoint with
WatchOptions.resume_from(lsn). The subscription reconnects by itself on a transient failure and
resumes from the last event it delivered.
Watch for ChangeOp.DISCONTINUITY. It does not mean an event was reordered - it means changes were
lost, and everything your consumer believes about that resource is stale until it re-snapshots.
The asynchronous client offers this as an iterator instead, which is the natural shape in asyncio:
async for event in await client.watch_graph(graph.id, WatchOptions.from_now()):
print(event.op, event.lsn)
That form does not reconnect. Checkpoint event.lsn and re-open with resume_from if the stream
ends.
Change streams are not available on a graph branch: a branch has no change log of its own, and the server refuses the subscription.
A complete example
from cyrock_db import CyrockDbClient, RetryableException
from cyrock_db.types import (
AUTO_ASSIGN_ID, Cardinality, CollectionDefinition, MetadataFieldDefinition,
MetadataFieldType, SearchRequest, Vector, VectorFieldDefinition,
)
with CyrockDbClient(api_key="your-api-key") as client:
collection = client.create_collection(project_id, CollectionDefinition(
name="papers",
vector_fields=(VectorFieldDefinition(name="embedding", dimension=384),),
metadata_fields=(
MetadataFieldDefinition(name="title", type=MetadataFieldType.STRING,
cardinality=Cardinality.HIGH, fulltext=True),
MetadataFieldDefinition(name="year", type=MetadataFieldType.INTEGER,
cardinality=Cardinality.LOW),
),
))
for paper in papers:
client.upsert_document(
collection.id, paper["doi"],
{"embedding": Vector(paper["embedding"])},
{"title": paper["title"], "year": paper["year"]},
)
try:
matches = client.search(collection.id, SearchRequest(
vector_field="embedding", vector=query_embedding, max_results=10,
))
except RetryableException:
matches = []
for match in matches:
print(f"{match.score:.3f} {match.document.metadata['title']}")
See also
-
Getting started - standing up a server
-
Java SDK - the same API for the JVM
-
REST API - the language-agnostic surface
-
CyQL - the query language