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.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.
Metadata
Release files for tarka-sdk 0.6.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.6.0.tar.gz | 261.1 kB | Without provenance | Details for tarka_sdk-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tarka_sdk-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for tarka_sdk-0.6.0-py3-none-any.whl |
Total release size: 503.5 kB
Release files / tarka_sdk-0.6.0.tar.gz
| Download URL | tarka_sdk-0.6.0.tar.gz |
|---|---|
| Size | 261.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0464f371895a775dfccb610cd1a09bfc759bb65f063595ecf159780928cc3fd7
|
|
BLAKE2b-256 checksum How to use checksums |
55d7bc2a4c427e96aa2037241d64c82a8aebabb08984fe82d3a64e78e88fdf2f
|
| 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.6.0-py3-none-any.whl
| Download URL | tarka_sdk-0.6.0-py3-none-any.whl |
|---|---|
| Size | 242.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
72a32942d758f9f8cc0e629144b69ffb4af42c5ccb9a84073849621626301633
|
|
BLAKE2b-256 checksum How to use checksums |
43550a3cf6e055618345190c1d44e87aa5a6940123e94184340d008c82320c63
|
| 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.6.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.