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.typedmarker. - 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,
bytesfor audio,datetimetimestamps, 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.grpcon 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.10.0 is available on PyPI:
python -m pip install tarka-sdk==0.10.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").
An HTTP service can act for the signed-in user whose request it is serving, without handling that user's token, with Database.from_platform("orders", act_as_invoking_user=True). Each call then sends Tarka-Act-As: invoking-user, and access is the user's own permissions narrowed by the workload's. It is off by default and works only in an HTTP service whose access enables identity.act_as_invoking_user, during a live invocation by a signed-in user: a call outside one, such as after the response was returned or from a realtime subscription that outlives it, is refused with 403 invoking_user_unavailable. It cannot be combined with on_behalf_of=. While acting is possible, discover() (see below) carries invocation.
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.
Platform services inside Tarka compute
Code running in a Function, a batch job, an Agent Host or a sandbox reaches object storage, other compute and project secrets at http://tarka with no credential: the platform authenticates the workload. Each service stays disabled until the workload's access enables it, when the workload is created or with SetWorkloadAccess, and then reaches only the buckets, Functions and secrets the access names.
from tarka import Platform
from tarka.platform import secret
stripe_key = secret("STRIPE_KEY")
with Platform() as tarka:
print(tarka.discover()["access"]) # what this workload may reach
assets = tarka.storage("assets")
assets.put("reports/q3.csv", csv_text, content_type="text/csv")
data = assets.get("reports/q3.csv")
page = assets.list("reports/", delimiter="/")
upload = assets.presign("videos/raw.mp4", "PUT", expires_in=600)
response = tarka.compute.invoke("resize", "/thumbnails", json={"key": "a.png"})
run = tarka.compute.run_job("nightly-report")
session = tarka.compute.create_session({"image": "python:3.13"}, timeout_seconds=120)
result = tarka.compute.exec(session["id"], ["python", "-c", "print(1)"])
tarka.compute.delete_session(session["id"])
| Service | Methods |
|---|---|
| Discovery | discover() |
| Secrets | secrets() returns every granted secret by name, secret(name) one value |
| Object storage | storage(bucket) with list, objects, get, stream, head, put, delete, presign |
| Functions | compute.invoke(function, path, method=, json=, content=, params=) returns the httpx.Response |
| Jobs | compute.run_job(job), compute.get_job_run(job, run_id) |
| Container sessions | compute.create_session, get_session, exec, delete_session |
discover(), secrets() and secret(name) are also functions of tarka.platform. AsyncPlatform has the same methods to await and supports async with. Pass base_url= to reach a local stand-in instead of http://tarka.
Object keys are paths such as reports/2026/q3.csv; the SDK escapes them. get returns the bytes exactly as stored, also for an object written with Content-Encoding. stream(key, headers=...) reads a large object, a range, or conditionally. An upload through the gateway takes at most 256 MiB; a presigned URL takes up to 5 GiB and needs internet egress. Job runs and sessions are JSON objects with the protobuf field names of JobRun, CodeSandbox and Execution. A Function's response is returned whatever its status.
A refusal raises PlatformError, a TarkaError whose code follows the HTTP status (permission_denied, not_found, resource_exhausted, ...) and whose reason is the gateway's own code, such as capability_disabled, bucket_not_found, object_not_found, secret_not_found, function_not_found, job_run_active or rate_limited. status is the HTTP status and retry_after the delay in seconds the gateway asks for; nothing is retried automatically. An answer to HEAD has no body, so head() reports only the status.
Git and the workload's API and MCP gateway need no SDK. Stock git (2.31 or later) clones and pushes http://tarka/git/{repository}.git. HTTP services and batch jobs already make git send the header; elsewhere set it once with git config --global http.http://tarka/.extraHeader 'Tarka-Workload: 1'. An MCP client reaches the workload's gateway at http://tarka/mcp, and one of several at http://tarka/gateways/{gateway}/mcp, when it sends the same header; its API routes are at http://tarka/api/{path}. To act for the invoking user there, add Tarka-Act-As: invoking-user to those headers, under the same conditions as act_as_invoking_user for databases. Storage, compute and secrets are always used as the workload.
from mcp.client.streamable_http import streamablehttp_client
headers = {"Tarka-Workload": "1"}
async with streamablehttp_client("http://tarka/mcp", headers=headers) as (read, write, _):
...
Metadata
Release files for tarka-sdk 0.10.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tarka_sdk-0.10.0.tar.gz | 324.9 kB | Without provenance | Details for tarka_sdk-0.10.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tarka_sdk-0.10.0-py3-none-any.whl | Python 3 | none | any | Details for tarka_sdk-0.10.0-py3-none-any.whl |
Total release size: 625.2 kB
Release files / tarka_sdk-0.10.0.tar.gz
| Download URL | tarka_sdk-0.10.0.tar.gz |
|---|---|
| Size | 324.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ee99891ac1b89d08fd41dff67a5598666dbae3cb182aeda374e55d823f597dc4
|
|
BLAKE2b-256 checksum How to use checksums |
8345d04a9a3f13ba4729ed5d14ee1f828ef783211860266a52ebf139a0d1c33e
|
| 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.10.0-py3-none-any.whl
| Download URL | tarka_sdk-0.10.0-py3-none-any.whl |
|---|---|
| Size | 300.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
933bdb2c6146b91bf5ca89b482d439d7a95a667832afe7f145eaa943aa355b97
|
|
BLAKE2b-256 checksum How to use checksums |
16ab77553496567ae84e35ff9263618846220bdebde8472b213c8711c6fc8d08
|
| 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.10.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.