Skip to main content

Tarka Python SDK

The official Python SDK for Tarka, with typed synchronous and asynchronous resources for inference, organizations, compute, storage, Git, and sandboxes.

models = client.models.list()
text = client.chat.text(model=model, prompt="Hello!")
sandbox = client.org(org_id).sandboxes.create(template=template)
execution = sandbox.run('print("Hello from Tarka")')
print(execution.status, execution.stdout)
  • Python 3.9+, with type hints, docstrings and a py.typed marker.
  • Friendly wrappers for all 77 RPCs in the pinned API contract.
  • Lists return lists; reads and writes return typed records; deletes return None.
  • Plain dictionaries for JSON, bytes for audio, datetime timestamps, lossless integers.
  • Sandbox handles with bounded polling and explicit recovery after interruption.
  • The same resource paths and behavior on sync and async clients.
  • The original three runtime dependencies: grpcio, protobuf, googleapis-common-protos.
  • Native stubs remain available only under client.grpc on the client.

Documentation · Runnable examples · Migration from 0.2 · RPC coverage and JavaScript parity

Inference uses tarka.inference.v1.InferenceService. Regenerate native gRPC clients when upgrading from the previous inference namespace; RPC paths and generated import paths now use v1. The resource API is unchanged.

Install this version

Version 0.6.0 is available on PyPI:

python -m pip install tarka-sdk==0.6.0

The distribution is tarka-sdk, imported as tarka. Installation needs no API repository or protoc. Existing 0.2.0 GitHub release artifacts use the older low-level interface; follow the migration guide when upgrading. See installation.

Quick start

import os
from tarka import TarkaClient

with TarkaClient(os.environ["TARKA_API_KEY"], timeout=30) as client:
    models = client.models.list()
    print([model.id for model in models])
    text = client.chat.text(
        model=os.environ["TARKA_MODEL"],
        prompt="Explain HTTP/2 in one sentence.",
        max_tokens=100,
    )
    print(text)

Reuse a client across calls. SDK-owned channels use TLS and bearer authentication at grpc.tarka.rest:443; close them on shutdown or use a context manager. Pass the token without Bearer. The application reads environment variables. Use an inference-scoped key for inference, an account token for control resources, and an account token or sandbox-scoped key for sandboxes. See authentication.

Predictable calls and results

Arguments are Python keyword parameters. No request messages or empty dictionaries are required, even when specifying only request settings:

client.models.list(timeout=10)
client.catalog.list(timeout=10)
client.catalog.list(modality="text", timeout=10)
client.chat.text(model=model, prompt="Hello", headers={"x-request-id": "example"})

Every call accepts timeout (seconds), headers (plain metadata), and cancel (an optional CancellationToken). Payload metadata remains a separate field. A per-call timeout overrides the client default. Ordinary RPCs have no SDK deadline if both are omitted; wait/run helpers default to a 60-second total budget.

Operation Result
list() Python list from one server response; no envelopes or hidden pagination
get(id), create(...), update(...) Typed record
delete(id) None after acknowledgement
revoke(...), cancel(...) Updated record/body
stream(...) Lazy, closeable iterator; async iterator on the async client
Sandbox list/get/create/wait The same handle classes for that client mode

Records live in tarka.types, support attribute access, and provide to_dict(). to_dict(json_safe=True) converts bytes to base64 and timestamps to ISO strings. Optional absent fields are None; counters keep full integer precision. API key creation adds a one-time .secret; storage credential creation adds .access_key_id, .secret_access_key, .endpoint, and .region. Store secrets at creation. Their repr omits secrets, but explicit serialization includes them.

Streaming and async

with client.chat.stream_text(model=model, prompt="Hello") as stream:
    for text in stream:
        print(text, end="", flush=True)

Use the stream context manager when iteration might end early. break alone does not guarantee cancellation in Python. A stream timeout covers its entire RPC.

import asyncio
import os
from tarka import TarkaAsyncClient

async def main() -> None:
    async with TarkaAsyncClient(os.environ["TARKA_API_KEY"], timeout=30) as client:
        models = await client.models.list()
        print([model.id for model in models])
        async with client.chat.stream_text(
            model=os.environ["TARKA_MODEL"], prompt="Hello"
        ) as stream:
            async for text in stream:
                print(text, end="", flush=True)

asyncio.run(main())

Await unary methods; do not await the method that creates a stream. Async clients use native grpc.aio, without blocking wrappers or private event-loop bridges.

Organization resources

Bind the organization once:

org = client.org(org_id)
keys = org.api_keys.list()
usage = org.usage.summary()
bucket = org.storage.buckets.create(name="example")
resource = org.compute.jobs.create(name="example", image="example/image:tag")

The scope also provides members, access_requests, invitations, quotas, inference_capture, repositories, and sandboxes. Root resources include user, organizations, invitations, git, models, catalog, chat, responses, ocr, document_layout, and audio. Control API examples include private GHCR agent hosts.

Sandbox recovery

from tarka import ExecutionOperationError

sandbox = client.org(org_id).sandboxes.get(sandbox_id)
try:
    execution = sandbox.run('print("hello")', timeout_seconds=30, timeout=60)
except ExecutionOperationError as error:
    execution = error.resume(timeout=60)
print(execution.status, execution.exit_code, execution.stdout)

run() waits for readiness, submits code, and waits for completion within one budget. Known executions resume by polling their ID. Unacknowledged mutations retain their original input and idempotency key for explicit replay within the API's 24-hour deduplication window. Nothing is retried automatically by the SDK. A timeout does not prove that remote execution stopped. A completed code failure returns an execution with status="failed"; inspect its status and exit code.

Async recoverable operations raise AsyncExecutionOperationError (or the matching sandbox/template error); use await error.resume(...). Native task cancellation remains an asyncio.CancelledError and retains the same recovery context. See sandboxes and errors.

Advanced native gRPC

from tarka.inference.v1 import inference_pb2

response = client.grpc.inference.ListModels(inference_pb2.ListModelsRequest(), timeout=10)

Raw stubs retain protobuf messages, native options and grpc.RpcError. Generated module paths and the pinned wire contract are unchanged. Normal resource methods raise TarkaError with readable codes such as permission_denied.

Development

uv sync --all-groups
make verify

make verify checks formatting, generation consistency, strict types, examples, local TLS/gRPC behavior and distribution builds. Runtime dependencies are unchanged. Development explains protobuf generation, the shared sync/async implementation, package checks, and the Python version matrix.

Apache-2.0. See LICENSE. Report security issues through the Tarka API security policy.

Gateway connection settings

Gateway create, update, get and list responses expose endpoints when routing is configured. api_base_url accepts published operation paths; api_audience is the exact OAuth resource without /api. mcp_url and mcp_audience are the same MCP endpoint. issuer identifies the environment's OAuth issuer. Use these server-provided settings instead of constructing URLs. They are available for setup before publication and do not grant access.

gateway.list_private_services() lists controller-observed services in the bound organization and realm. Set a target's service_id and service_path instead of url for a private destination. Only a ready service can be published; a redeployment requires a new gateway publication. Its exact credential scope is tarka-service://<service_id> in allowed_origins.

Trusted agent harness

Use RuntimeClient in the trusted server-side harness. Supply an OAuth token provider for the realm's exact runtime resource and runtime.execute; the server derives the user, bound agent and consent. Platform API keys cannot start customer runs.

from tarka import RuntimeClient, RuntimePermission

with RuntimeClient(
    origin=gateway_origin,
    realm_id=realm_id,
    token_provider=current_runtime_oauth_token,
) as runtime:
    with runtime.run(
        gateway_id=gateway_id,
        transport="api",
        permissions=[RuntimePermission(capability_id, "invoke")],
    ) as run:
        response = run.api("GET", "/records")
        try:
            tool_result = response.read()
        finally:
            response.close()

AsyncRuntimeClient offers the same lifecycle with async with and awaited methods. For MCP, create a run with transport="mcp", then give its mcp_transport() to a dedicated httpx.Client or httpx.AsyncClient and use run.audience as the MCP endpoint. The adapter rejects every other destination.

Only register specific tool closures and their results with the model. Keep runtime clients, handles and token providers out of prompts, tool arguments, agent workspaces and logs. Runtime metadata is safe to inspect; credentials are kept internally and omitted from repr. The SDK does not sandbox hostile code running in the same process.

The harness renews a lease near expiry when making a request; concurrent use is serialized. A failed or uncertain renewal disables further tool calls. Issuance, renewal and tool actions are never retried automatically. run.finish() revokes access; context managers complete on success and attempt cancellation on error. A cleanup failure does not replace the original exception. Read and close streamed responses promptly. Renewing while an earlier stream is still being read may cause its server authorization check to terminate that stream.

Independent messaging consumers

After a customer links their provider account and approves the channel's tool scope, an assigned agent worker can consume messages with its autonomous Ory token for the same runtime audience. Both customer and agent need channel use permission. The gateway derives customer identity and tool scope.

from contextlib import aclosing
from tarka import AsyncRuntimeClient

async with AsyncRuntimeClient(
    origin=gateway_origin, realm_id=realm_id,
    token_provider=current_worker_oauth_token,
) as runtime:
    async with aclosing(runtime.messages(channel_id)) as messages:
        async for message in messages:
            # Pass only the prompt as user input. Build tool closures around
            # message.api(...) or message.mcp_transport() inside your harness.
            result = await execute_agent_turn(message.prompt, message)
            await message.reply(result)

claim_message(channel_id) returns one message or None. RuntimeClient provides synchronous equivalents; use contextlib.closing for its iterator. The iterator polls empty queues every five seconds and cancels an unfinished run when advancing or closing. A private reply() finishes the run and accepts at most 2,000 Unicode characters. Recipients are never caller-selected. Failures propagate; uncertain claims and replies are never retried. Keep the message handle in trusted harness code. Its repr omits both prompt and secrets.

Publishing

The SDK release workflow builds and tests both distributions, saves their SHA-256 checksums, and uploads a reviewable release artifact. A dry run is the default. Publishing requires running release.yml on main with publish=true; it publishes those exact tested files and attaches them to a GitHub release.

Configure PyPI's trusted publisher for project tarka-sdk, owner TarkaHQ, repository sdk-python, workflow release.yml, and environment pypi. For an unpublished project, use a pending publisher. No PyPI token belongs in this repo. See uv trusted publishing.

Managed databases

org.databases manages a project's databases, and org.databases.records(database_id) reads and writes their records over gRPC. Both use the client's session or a tk_live_ key with the databases scope, and both exist on TarkaClient and TarkaAsyncClient.

from tarka import RecordFileInput, TarkaClient, TarkaError, record_rejection

with TarkaClient(access_token) as client:
    org = client.org(org_id)
    database = org.databases.create(project_id=project_id, name="ledger")
    org.databases.releases(database.id).submit(
        {
            "database": database.id,
            "collections": [
                {
                    "id": "notescollection",
                    "name": "notes",
                    "type": "base",
                    "fields": [{"id": "textcontent", "name": "body", "type": "text"}],
                }
            ],
        }
    )

    notes = org.databases.records(database.id).collection("notes")
    note = notes.create({"body": "First note"})
    page = notes.list(filter="body ~ 'First'", sort="-created")
    with notes.subscribe() as changes:  # leaving the block closes the stream
        for change in changes:
            print(change.action, change.record["id"])
            break

Records are plain dictionaries. Record methods are list, get, create, update, delete, download and subscribe on a collection, and batch, health and subscribe on the database. Pass files=[RecordFileInput(field, filename, content)] to create or update to store files; one request may not exceed 32 MiB. The first call starts a sleeping database, and an open subscription keeps it running. When the database refuses a write, record_rejection(error) returns its status, message and per-field codes:

try:
    notes.create({"body": ""})
except TarkaError as error:
    rejection = record_rejection(error)
    if rejection:
        print(rejection.status, rejection.data)

The remaining control operations sit beside create:

Operation Method
Rename, toggle backups or public HTTPS, select a gateway, connect a Git schema databases.update(id, expected_version=..., ...)
Delete; restore points are kept for seven days databases.delete(id, expected_version=...)
Replace the contents with a restore point, also for a deleted database databases.restore(id, restore_point_id=..., expected_version=...)
List restore points, or request one now databases.restore_points(id).list() and .create()
List, attach and detach agent hosts databases.attachments(id).list(), .set(...), .detach(...)
Release history, approval of a destructive release, manifests databases.releases(id).list(), .approve(...), .manifest()

delete, restore and restore_points(id).create() return as soon as the request is recorded. Read the database again for state, operation_error and backup_requested_at.

PocketBase-compatible client

client.database(org_id, database_id) returns a PocketBase client for the same records over HTTP, for code written against PocketBase.

with TarkaClient(access_token) as client:
    with client.database(org_id, database_id) as db:
        notes = db.collection("notes")
        note = notes.create({"title": "First note"})
        page = notes.get_list(1, 20, {"sort": "-created", "fields": "id,title"})
        print([item.title for item in page.items])

TarkaAsyncClient.database(org_id, database_id) supports async with and awaitable collection methods. Both clients support record CRUD, filters, pagination, relation expansion, file uploads, atomic batches and realtime. Read IAM-protected file bytes with db.download_file(record, record.attachment). Use notes.subscribe(callback) or notes.subscribe_one(record_id, callback) for changes. Close the database or unsubscribe to release the stream and allow the database to sleep.

Inside Tarka compute

Code running in a Function, a batch job, an Agent Host or a sandbox needs no token and no database ID. The platform authenticates the workload at http://tarka.

from tarka import Database

with Database.from_platform() as db:  # this workload's own database
    db.collection("notes").create({"title": "first", "stars": 3})

with Database.from_platform(project=True) as shared:  # the project's default database
    shared.collection("events").get_list()

with Database.from_platform("orders") as orders:  # a named database in the project
    orders.collection("items").get_full_list()

The workload's own database and the project's default database are created the first time they are used, and a collection is created the first time a record is written to it. The first call to a sleeping database waits for it to start. Pass a user's project identity token as on_behalf_of= to act for that user instead of as the workload. Which databases a workload may reach is its access, set when it is created or with SetWorkloadAccess; a sandbox reaches none until that is switched on. AsyncDatabase.from_platform() takes the same arguments. Models are reachable the same way with any OpenAI client: OpenAI(base_url="http://tarka/v1", api_key="tarka").

To connect to a published endpoint, import Database or AsyncDatabase from tarka and pass the generated database URL and an IAM token. A zero-argument callable can supply a fresh token on each request. Keep developer credentials on the server.

Tarka IAM handles sign-in. Deploy schema and rules through database releases. The managed data API exposes records, batches, files, realtime and health. PocketBase password sign-in, admin settings and schema-management endpoints use separate Tarka workflows.

Metadata

Release files for tarka-sdk 0.9.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 tarka-sdk 0.9.0
File Size Uploaded Provenance Actions
tarka_sdk-0.9.0.tar.gz 308.0 kB Without provenance Details for tarka_sdk-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tarka-sdk 0.9.0
File Interpreter ABI Platform Actions
tarka_sdk-0.9.0-py3-none-any.whl Python 3 none any Details for tarka_sdk-0.9.0-py3-none-any.whl

Total release size: 597.2 kB

Release files / tarka_sdk-0.9.0.tar.gz

Download URL tarka_sdk-0.9.0.tar.gz
Size 308.0 kB
Tags Source
SHA-256 checksum
How to use checksums
23de73e8a61922e90ba4da8480e9b0fcc8d0aa5a8b799aaea2698d562875f3bd
BLAKE2b-256 checksum
How to use checksums
ee9081c660b027c34f9ca2d60daac98b43bdbc073d57fb7c2c2397a6d43e71c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / tarka_sdk-0.9.0-py3-none-any.whl

Download URL tarka_sdk-0.9.0-py3-none-any.whl
Size 289.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1330f2f98c923bb5229d099c6247cc191ead5204be41fb2b3d55f2a1a155b634
BLAKE2b-256 checksum
How to use checksums
7740191642a02c012ed96f2ef05e714712069c85ab652a231586d49f28dfdcb9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for tarka-sdk 0.9.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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