Metadata-Version: 2.4
Name: pramaan
Version: 0.1.0
Summary: Pramaan API client: call any Pramaan capability from Python, plus payments and testing helpers
Project-URL: Homepage, https://pramaan.dev
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.28.1
Provides-Extra: test
Requires-Dist: pytest==8.4.2; extra == "test"
Requires-Dist: mypy==1.18.2; extra == "test"

# Pramaan Python client

Python 3.10+ client for the Pramaan API.

```sh
pip install pramaan
```

## Versions

Patch releases (0.1.x) only fix things; anything that could break your code ships in a new
minor or major version with a changelog, so `pip install -U` within your pinned range is safe.
The HTTP API it talks to (`/v1`) stays compatible with older clients.

To work on this package from the repository root:

```sh
python3 -m venv packages/sdk-python/.venv
packages/sdk-python/.venv/bin/python -m pip install -e packages/sdk-python
```

## Quickstart

```python
import os
from pramaan import Pramaan, RunOptions, PramaanError

with Pramaan(os.environ["PRAMAAN_API_KEY"]) as client:
    info = client.info("web.search")
    print(info["effect_class"])
    estimate = client.capabilities.estimate("web.search", {"query": "example"})
    print(estimate["price_max_micro"])
    options = RunOptions(idempotency_key="search-example-1")
    result = client.capabilities.run("web.search", {"query": "example"}, options)
    for item in result["results"]:
        print(item["title"], item["url"])
    descriptions = client.capabilities.describe_all(namespace="web")
    print(len(descriptions))
    print(client.capabilities.get("web.search")["description"])
```

`AsyncPramaan` has the same methods: use `async with` and await network methods.
`info()` remains synchronous and offline. Capability results and discovery/outcome dictionaries preserve API field names;
jobs expose `id` in place of `job_id`.
`capabilities.run` is typed by capability id; `client.run` accepts unknown or new ids.
Dictionary types (`TypedDict`) describe the wire data without copying it into model objects.
Optional keys remain optional; unknown schemas and recursive back-edges use `Any`.

`run` returns a job for an asynchronous capability. `call` waits and returns its result,
or raises on a failed/cancelled job. `jobs.wait(id, timeout=60, interval=2)` returns any terminal
job, including failed or cancelled jobs. Times are seconds; polling grows from at least two
seconds to 30 seconds. The default deadline is 31 minutes.

## Outcomes

```python
from pramaan import RunOptions

input = {"domain": "example.com"}
plan = client.outcomes.estimate("company.research", input)
# Show the input and plan["steps"] to a person and get their approval if required.
report = client.outcomes.run(
    "company.research", input,
    RunOptions(plan=plan["plan"], idempotency_key="research-example-1"),
)
print(report["status"], report.get("result"))
```

Use `outcomes.list()` and `outcomes.get(id)` to inspect outcomes. RunOptions also accepts
`options` and `basis` for the outcome body, and `member` and `approved_by` for approvals.
The plan travels in `Pramaan-Plan`. Long outcomes are polled automatically.

## Streamed chat replies

```python
with client.stream("llm.chat", {"messages": [{"role": "user", "content": "Say hello."}]}) as events:
    for event in events:
        if event["type"] == "text_delta":
            print(event["text"], end="")
        elif event["type"] == "done":
            reply = event["result"]          # the whole reply, as run() returns it
            print(event["price_micro"])      # what it cost
```

Async: `async with client.stream(...) as events:` then `async for event in events:`.
Events are `text_delta`, `tool_call_start`, `tool_call_delta`, `tool_call_end`, `usage` and last `done`
(types in `pramaan.StreamEvent`). A failure before or during the stream raises `PramaanError`; one
that arrives mid-stream comes after the events already received, and the stream then ends. A body that
ends without `done` raises a retryable `upstream_unavailable`. Leaving the `with` block (or
`close()` / `aclose()`) closes the connection and stops the call; what was generated is still charged.
A stream is never retried and sends an `Idempotency-Key` only if you pass one. Connect limit 10 s;
60 s without data (`stream_timeout=`; the API sends a keep-alive every 15 s).

## Errors

```python
try:
    client.capabilities.run("web.search", {"query": "example"})
except PramaanError as error:
    print(error.code, error.reason, error.request_id)
    if error.effect == "none":
        print("Nothing happened; you can change the request and try again.")
    else:
        print("Check what happened before repeating an action.")
```

Errors expose `code`, `retryable`, `status`, `request_id`, `slot`, `reason` and `effect`.
Only an explicit API `effect: "none"` proves nothing happened. API reads, estimates and known
read-only capabilities/outcomes retry network errors, 429 and 5xx twice by default; other calls
never retry automatically. Retry attempts keep the same caller-supplied idempotency key.
`accounts.list()`, `routing.get()` and `routing.set(rules, version)` mirror the existing HTTP helpers.
Routing saves send `If-Match` and never retry automatically. Keys are never created implicitly. Set `max_retries=0` to turn retries off. Every request has a timeout (`timeout=`, default 300 s
with a 10 s connect limit), and redirects are never followed, so the key stays with the base address.
A timeout counts as a network failure: read-only calls retry, actions do not.

## Files

```python
handle = client.files.upload(b"example", kind="data", content_type="text/plain")
fresh = client.files.get(handle["fileId"])
client.files.delete(handle["fileId"])
```

Uploads send raw bytes, never multipart bodies. `files.list()` lists handles. Pass a handle's
`fileId` into a capability that accepts it.

## Development and CI

```sh
packages/sdk-python/.venv/bin/python -m pip install -e 'packages/sdk-python[test]'
packages/sdk-python/.venv/bin/python -m pytest packages/sdk-python/tests -q
REGENERATE_OFFLINE=1 PARITY_PORT=9102 bash scripts/coordinator/regenerate.sh
pnpm check
```

`pnpm check` uses the local virtual environment, otherwise `python3`, or
`PRAMAAN_TEST_PYTHON` if set. No Python means an explicit skip; installed Python with missing
test dependencies fails with installation instructions. CI should install Python 3.10 or newer,
then run `python3 -m pip install -e 'packages/sdk-python[test]'` before `pnpm check`.
Tests use fake transports only. Generated-file freshness compares against the same parity API
snapshot used by the TypeScript generator, with no live provider calls.

Hand-written: request policy, sync/async drivers, resources, options, errors and file handles.
Generated: capability request/result dictionary types, id literals, catalogues and generic
method overloads. Both languages regenerate through the existing SDK generate command.
The generated files total roughly 7.6 MB for this catalogue; type definitions are loaded only
when imported explicitly, while runtime clients load just the metadata registry.

Differences from TypeScript: seconds instead of milliseconds; Python dictionaries retain wire
field names; no namespace shortcuts; files are supported from the API contract because the
TypeScript core has no file helper. Browser voice and webhook signature helpers are outside this
HTTP-client task. Streamed events keep the API's field names (`price_micro`, `finishReason`), where TypeScript
renames `price_micro` to `priceMicro`.
One runtime dependency, `httpx==0.28.1`, supports both transports; pytest and mypy are test-only.
