Metadata-Version: 2.5
Name: tarka-sdk
Version: 0.6.0
Summary: Official Python SDK for Tarka: typed sync and async resource clients
Project-URL: Homepage, https://tarka.rest
Project-URL: Repository, https://github.com/TarkaHQ/sdk-python
Project-URL: Issues, https://github.com/TarkaHQ/sdk-python/issues
Author: Tarka
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: googleapis-common-protos<2,>=1.70.0
Requires-Dist: grpcio<2,>=1.74.0
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: protobuf<7,>=6.31.1
Description-Content-Type: text/markdown

# Tarka Python SDK

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

```python
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](docs/index.md) · [Runnable examples](examples/) ·
[Migration from 0.2](docs/migration.md) · [RPC coverage and JavaScript parity](docs/api-reference.md)

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](https://pypi.org/project/tarka-sdk/0.6.0/)**:

```sh
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](docs/installation.md).

## Quick start

```python
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](docs/authentication.md).

## Predictable calls and results

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

```python
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

```python
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.

```python
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:

```python
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](docs/control-api.md) include private GHCR agent hosts.

## Sandbox recovery

```python
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](docs/sandboxes.md) and [errors](docs/errors.md).

## Advanced native gRPC

```python
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

```sh
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](docs/development.md) explains protobuf generation, the shared sync/async
implementation, package checks, and the Python version matrix.

Apache-2.0. See [LICENSE](LICENSE). Report security issues through the
[Tarka API security policy](https://github.com/TarkaHQ/api/blob/main/SECURITY.md).

## 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.

```python
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.

```python
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](https://docs.astral.sh/uv/guides/package/).
