Skip to main content

Antfly Python SDK

PyPI version Python

Python SDK for Antfly - a distributed key-value store and search engine.

Supported Python versions: 3.11 through 3.14.

The examples here target the pinned development source below. The inspected PyPI 0.0.2.dev2 wheel lacks AntflyClient.query; TestPyPI 0.0.1 has query but lacks current read-requirement helpers and media chunking. TestPyPI is not a fallback for this API surface (package contents checked 2026-10-22).

Installation

pip install "antfly-sdk @ git+https://github.com/antflydb/antfly.git@ddba6584b38b59c62e261ef63e0374dc1f711617#subdirectory=py/packages/sdk"

Quick Start

from antfly import AntflyClient

# Initialize client
client = AntflyClient(
    base_url="http://localhost:8080",
    username="admin",
    password="password"
)

# Create a table
client.create_table(
    name="users",
    num_shards=4,
    schema={
        "default_type": "user",
        "document_schemas": {
            "user": {
                "schema": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "email": {"type": "string"},
                        "age": {"type": "integer"},
                        "created_at": {"type": "string", "format": "date-time"}
                    }
                }
            }
        }
    }
)

# Insert data
client.batch(
    table="users",
    inserts={
        "user:1": {
            "name": "John Doe",
            "email": "john@example.com",
            "age": 30
        },
        "user:2": {
            "name": "Jane Smith",
            "email": "jane@example.com",
            "age": 25
        }
    }
)

# Query data
results = client.query(
    table="users",
    full_text_search={"query": "John"},
    limit=10
)

# Get specific record
user = client.get(table="users", key="user:1")

Features

  • Simple API: Intuitive interface for all Antfly operations
  • Type Safety: Full type hints for better IDE support
  • Authentication: Built-in support for basic authentication
  • Error Handling: Comprehensive error handling with custom exceptions
  • Auto-generated Client: Based on OpenAPI specification for accuracy

Native KV checkpoints

The native Gemma 4 E4B CUDA route can export a binary checkpoint and resume it with the same model revision, tokenizer, template, and KV layout. The streaming helpers keep checkpoint transfers out of Python's full-response buffers and publish a downloaded file only after integrity checks succeed.

FP16, FP8 and rotated4 checkpoints passed the bounded E4B Q4_0/L4/eager-CUDA production qualification at 8K and 32K. The qualification record documents the tested model revision, answer-quality coverage and latency limits.

Configure the serving runtime and inference memory budgets using the native checkpoint serving guide. The default scratch budget is insufficient for preparation.

from pathlib import Path
from antfly import AntflyClient
from antfly.client_generated.models import InferenceGenerateRequest

client = AntflyClient("http://localhost:8080", timeout=1800)
request = InferenceGenerateRequest.from_dict({
    "model": "google/gemma-4-E4B-it-qat-q4_0-gguf",
    "messages": [{"role": "user", "content": Path("history.txt").read_text()}],
    "max_tokens": 64,
    "temperature": 0,
    "chat_template_kwargs": {"enable_thinking": False},
})
checkpoint = client.prepare_native_kv_checkpoint(request, "history.kv")  # lossless f16 storage
# Optional fitted-history FP8 disk encoding with validated f16 fallback:
# checkpoint = client.prepare_native_kv_checkpoint(request, "history-fp8.kv", encoding="fp8")
# Optional V4 compressed CUDA state; no experimental process switch required:
# checkpoint = client.prepare_native_kv_checkpoint(request, "history-rotated4.kv", encoding="rotated4")
# Use encoding="f32" for legacy V2 readers.
print(checkpoint.metadata["outcome"], checkpoint.metadata["global_savings_ratio"])

# The server can be restarted before this call, using the same model revision.
result = client.resume_native_kv_checkpoint(request, "history.kv")
print(result.choices[0].message.content)

Preparation generates no answer. unchanged_insufficient_savings means the file contains the exact original cache because fitting did not meet the savings threshold. Resume requests supply the full messages; their rendered tokens must extend the saved prefix exactly. A different model revision or rewritten prefix is rejected. resume_native_kv_checkpoint_stream is a context manager yielding SSE chunks; exiting its context closes both the upload file and response. Set the client timeout to cover original prompt ingestion and compaction.

Development

Setup

  1. Clone the repository
  2. Install development dependencies:
uv sync

Generate Client

The SDK uses an auto-generated client based on the Antfly OpenAPI specification:

make generate

Run make check-generation-completeness to fail on any endpoint or schema the generator omits. The normal generation target remains available while existing upstream incompatibilities are resolved.

Run Tests

make test

Build Package

make build

Documentation

make docs will generate the documentation in the docs/ folder.

License

Apache License 2.0

Warning

The strict completeness check currently reports models that cannot be autogenerated from the spec.

Model-aware media chunks

client.chunk_and_embed accepts text, PDF, images, GIF, audio and video and returns typed descriptor/vector pairs:

response = client.chunk_and_embed({
    "input": "A long document…",
    "embedding": {"model": "embeddinggemma2", "task_type": "RETRIEVAL_DOCUMENT"},
    "policy": {"target_tokens": 500, "overlap_tokens": 50},
    "include_content": True,
})
for chunk in response.data:
    print(chunk.descriptor.coordinates, chunk.embedding)

Check status, gaps and next_continuation before declaring complete coverage. Resume with the same request plus continuation. For bounded delivery, use with client.chunk_and_embed_stream(request) as events: and consume start context, chunk objects and the final response. Exiting the context closes the connection; EOF without terminal coverage raises. Retain the start context's model identity with vectors. Set embedding.execute to False for planning only. Inline media uses {"type": "media", "mime_type": ..., "data": ...} with base64 data; immutable HTTP/S3 sources use a version-pinned source reference. See the shared contract for policies, security, limits and database integration.

Reliable writes and cursor reads (0.2.1)

batch(..., sync_level="full_index") returns a typed BatchResponse. Inspect status: committed_pending has not established requested visibility, while committed_repair_required means the document committed but materialization needs repair. Do not replay a committed mutation to repair indexing. Timeouts can have unknown commit outcomes; this client does not automatically retry them. Atomic transforms are accepted as a list of mappings.

Lookup raises AntflyNotFoundError only for HTTP 404; other HTTP errors retain status_code on AntflyHTTPError. get(..., fields=["_embeddings"]) reads persisted vectors, and get_with_version() returns the document and exact OCC version token. Ordered pagination must replay the response's remote_snapshot alongside search_after; query() exposes both.

embed(), rerank(), and models() provide bounded public inference JSON access. request() is the public authenticated transport for other /db/v1/ and /ai/v1/ operations. Use close() or a context manager to release the client's HTTP pool.

Optional source management

from antfly.sources import SourcesClient

with SourcesClient("https://sources.example.com/sources/v1", management_token) as sources:
    run = sources.start_run(source_id, submission_key)
    receipt = sources.run(source_id, run["id"])

The base URL is an explicit Go-server or Colony management mount. Credentials and ingestion stay there; these operations do not target the Antfly database listener. Reuse the same submission key when resolving an ambiguous response. Inspect run outcome/completeness as well as execution state. StandaloneSourcesClient in the same module provides standalone credential and legacy profile operations.

Metadata

Release files for antfly-sdk 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for antfly-sdk 0.3.0
File Size Uploaded Provenance Actions
antfly_sdk-0.3.0.tar.gz 1.3 MB With provenance Details for antfly_sdk-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for antfly-sdk 0.3.0
File Interpreter ABI Platform Actions
antfly_sdk-0.3.0-py3-none-any.whl Python 3 none any Details for antfly_sdk-0.3.0-py3-none-any.whl

Total release size: 4.4 MB

Release files / antfly_sdk-0.3.0.tar.gz

Download URL antfly_sdk-0.3.0.tar.gz
Size 1.3 MB
Tags Source
SHA-256 checksum
How to use checksums
9e3ee4e7b3193090c7613f4e6fd8b42c3785d39592c4f20a36971a666003c12a
BLAKE2b-256 checksum
How to use checksums
f55f58edc76f7b14ee11561213a430e06c09023477e31364c349734e81633caf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / antfly_sdk-0.3.0-py3-none-any.whl

Download URL antfly_sdk-0.3.0-py3-none-any.whl
Size 3.1 MB
Tags Python 3
SHA-256 checksum
How to use checksums
3aefa85caea09fb75238e6b447d67bf747d522ec10fb7ab019f2c86b260e6350
BLAKE2b-256 checksum
How to use checksums
9e641c1ba4246f01578db3d13c276af96ede853042a566b841016f3feafa5938
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for antfly-sdk 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for antfly_sdk-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page