Metadata-Version: 2.5
Name: isolate-tx
Version: 0.1.0
Summary: Python client for Isolate, a transaction server that keeps concurrent AI agents from overwriting each other's work.
Project-URL: Homepage, https://github.com/tathagata1010/isolate-tx
Project-URL: Repository, https://github.com/tathagata1010/isolate-tx
Project-URL: Documentation, https://github.com/tathagata1010/isolate-tx/tree/main/clients/python#readme
Project-URL: HTTP API, https://github.com/tathagata1010/isolate-tx/blob/main/docs/http-api.md
Project-URL: Issues, https://github.com/tathagata1010/isolate-tx/issues
Author: Isolate contributors
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,concurrency,crewai,langgraph,llm,multi-agent,transactions
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# isolate-tx

The official Python client for [Isolate](https://github.com/tathagata1010/isolate-tx),
a transaction server for AI agents that share state.

When two agents read the same data, think for a few seconds, and then write, one of them can
silently overwrite the other. Isolate gives each agent step a transaction: reads come from a
consistent snapshot, writes stay private until commit, and a conflicting commit is rejected so the
step can be retried on fresh data. Irreversible actions (refunds, emails) are queued and sent only
after commit.

- Python 3.9+, zero runtime dependencies (standard library only)
- Sync and asyncio APIs, fully typed (`py.typed`)
- Automatic retries with backoff for conflicts

## 30-second quickstart

Start a server:

```bash
docker run -p 127.0.0.1:7070:7070 ghcr.io/tathagata1010/isolate
```

Install the client:

```bash
pip install isolate-tx
```

Use it:

```python
from isolate_tx import Isolate

iso = Isolate()  # uses $ISOLATE_URL, default http://localhost:7070

with iso.transaction(agent="hello") as tx:
    tx.write("greetings/en", "hello")

print(iso.get("greetings/en"))  # hello
```

The package is called `isolate-tx` on PyPI and imported as `isolate_tx`.

## The refund example

Two support agents each want to approve a $70 refund from the same $100 budget. Without
coordination, both read $100, both approve, and $140 goes out. With a `serializable` transaction the
second commit fails with a conflict, `run` retries it, the retry reads the new $30 balance, and the
agent declines.

```python
from isolate_tx import Isolate

iso = Isolate()
BUDGET = "refunds/account-42"   # balance in cents, stored as a string


def approve_refund(tx, amount_cents: int) -> bool:
    available = int(tx.read(BUDGET) or "0")
    # ... call your LLM here; this can take seconds ...
    if available < amount_cents:
        return False
    tx.write(BUDGET, str(available - amount_cents))
    tx.after_commit("issue-refund", {"account": "42", "amount": amount_cents})
    return True


approved = iso.run(
    lambda tx: approve_refund(tx, 7000),
    agent="refund-agent",
    isolation="serializable",
)
```

`after_commit` queues a webhook that the server sends only after the transaction commits, so a
failed or retried attempt never sends money. The effect name (`issue-refund`) must be configured on
the server, for example `-e ISOLATE_EFFECTS="issue-refund=https://payments.internal/refund"`.

[`examples/refund_race.py`](examples/refund_race.py) runs this race with two threads, once with
`read_committed` and once with `serializable`:

```text
READ_COMMITTED  $140.00 refunded from a $100.00 budget; recorded balance $30.00
                refunds issued: 2; retries: 0; invariant: VIOLATED
SERIALIZABLE    $70.00 refunded from a $100.00 budget; recorded balance $30.00
                refunds issued: 1; retries: 1; invariant: PRESERVED
```

## `run` vs. the context manager

**`iso.run(fn, ...)`** is what you want most of the time. It begins a transaction, calls `fn(tx)`,
commits, and returns what `fn` returned. If the commit (or any call) fails with a retryable abort,
it begins a new transaction with `retryOf` set to the failed attempt's id and calls `fn` again,
with exponential backoff and full jitter (10 ms base, 1 s cap, 8 attempts by default). Because `fn`
can run more than once, keep side effects in `tx.after_commit`.

```python
result = iso.run(fn, agent="planner", isolation="serializable", max_attempts=8)
```

The decorator form injects `tx` as the first argument:

```python
@iso.transactional(agent="refund-agent", isolation="serializable")
def approve(tx, amount_cents):
    ...

approve(7000)
```

**`with iso.transaction(...) as tx:`** runs exactly one attempt. It commits when the block ends
normally (the `CommitResult` is in `tx.result`) and aborts if the block raises. A conflict raises
`TxAborted` from the end of the `with` block; retrying is up to you.

```python
from isolate_tx import TxAborted

try:
    with iso.transaction(agent="refund-agent", isolation="serializable") as tx:
        budget = tx.read_json("budgets/42", default={"cents": 0})
        budget["cents"] -= 7000
        tx.write_json("budgets/42", budget)
        tx.record_tokens(1850)          # counts as useful or wasted in /v1/stats
    print("committed at", tx.result.commit_ts)
except TxAborted as e:
    if e.retryable:
        ...  # begin again with iso.transaction(..., retry_of=e.tx_id)
```

### Transaction methods

| Method | Does |
|---|---|
| `tx.read(key)` | Value at the snapshot, or `None` |
| `tx.read_many(keys)` | `dict[key, str \| None]` in one round trip |
| `tx.read_json(key, default=None)` | `json.loads` of the value |
| `tx.write(key, value)` | Buffer a string value; `None` deletes |
| `tx.write_many(mapping)` | Several writes in one round trip |
| `tx.write_json(key, obj)` | `json.dumps` and write |
| `tx.delete(key)` | Same as `write(key, None)` |
| `tx.after_commit(name, payload)` | Queue a server-configured effect; non-string payloads are `json.dumps`-ed |
| `tx.record_tokens(n)` | Add tokens spent; returns the running total |
| `tx.commit()` / `tx.abort()` | Finish explicitly (both optional inside `with` or `run`) |
| `tx.info()` | Server-side status of the transaction |

Transaction options (all keyword, all optional except `agent`): `isolation` (`"read_committed"`,
`"snapshot"`, `"serializable"`), `policy` (`"optimistic"`, `"pessimistic"`, `"adaptive"`),
`expected_tokens`, `lock_timeout_ms`, `idle_timeout_ms`. Options you leave out are not sent, so the
server defaults apply (`snapshot`, `optimistic`).

Outside a transaction: `iso.get(key)`, `iso.stats()`, `iso.health()`.

### Configuration

```python
Isolate(url=None, api_key=None, timeout=30.0)
```

`url` falls back to `ISOLATE_URL`, then `http://localhost:7070`. `api_key` falls back to
`ISOLATE_API_KEY` and is sent as `Authorization: Bearer <key>`. Ids and timestamps from the server
are strings (they are 64-bit values).

## Async

```python
import asyncio
from isolate_tx import AsyncIsolate

iso = AsyncIsolate()

async def approve(tx, amount_cents):
    available = int(await tx.read("refunds/account-42") or "0")
    if available < amount_cents:
        return False
    await tx.write("refunds/account-42", str(available - amount_cents))
    await tx.after_commit("issue-refund", {"amount": amount_cents})
    return True

async def main():
    ok = await iso.run(lambda tx: approve(tx, 7000), agent="refund-agent", isolation="serializable")

    async with iso.transaction(agent="auditor") as tx:
        print(await tx.read("refunds/account-42"))

asyncio.run(main())
```

`AsyncIsolate` has the same methods as `Isolate`, including `@iso.transactional` for `async def`
functions. It runs the synchronous client in worker threads with `asyncio.to_thread`. That keeps
the package free of dependencies (the standard library has no async HTTP client) and never blocks
the event loop; a round trip to Isolate is small next to an LLM call.

## Errors

Every error is an `IsolateError` with `.status`, `.error`, `.message`, `.reason`, `.retryable`,
`.tx_id` and the raw `.body`.

| Exception | HTTP | `error` | What to do |
|---|---|---|---|
| `InvalidRequest` | 400, 413 | `invalid_request`, `too_large` | Fix the request |
| `Unauthorized` | 401 | `unauthorized` | Set `api_key` / `ISOLATE_API_KEY` |
| `TransactionNotFound` | 404 | `tx_not_found` | Begin a new transaction |
| `TxAborted` | 409 | `aborted` | If `.retryable`, retry with `retry_of=e.tx_id` (`run` does this) |
| `TransactionNotActive` | 409 | `not_active` | The transaction already finished; begin a new one |
| `UnknownEffect` | 422 | `unknown_effect` | Configure the effect on the server or fix the name |
| `TooManyTransactions` | 429 | `too_many_transactions` | Back off and retry (`run` does this) |
| `InDoubt` | 500 | `in_doubt` | Outcome unknown; check after the server restarts, do not retry blindly |
| `IsolateError` | 500 | `internal_error` | Report it |
| `Fenced` | 503 | `fenced` | Talk to the new coordinator |
| `IsolateConnectionError` | (none) | `connection_error` | Server unreachable or timed out (`status == 0`) |

`TxAborted.reason` is one of `WRITE_WRITE_CONFLICT`, `READ_WRITE_CONFLICT`, `WOUNDED`,
`LOCK_TIMEOUT` (retryable), or `USER_ABORT`, `IDLE_TIMEOUT`, `STEP_FAILED`, `INTERRUPTED`,
`INTERNAL_ERROR`, `FENCED` (not retryable).

## Using it with agent frameworks

These are illustrative patterns, not official integrations. The idea is the same everywhere: wrap
the step that reads and writes shared state in `iso.run`, so the read, the decision and the write
commit together or retry together.

### LangGraph (illustrative)

Wrap a node's body. The graph state carries inputs; shared business data lives in Isolate.

```python
from isolate_tx import Isolate

iso = Isolate()

def refund_node(state: dict) -> dict:
    def step(tx):
        available = int(tx.read(f"budgets/{state['account']}") or "0")
        decision = llm_decide(state["ticket"], available)   # your model call
        if decision.approve and decision.amount <= available:
            tx.write(f"budgets/{state['account']}", str(available - decision.amount))
            tx.after_commit("issue-refund", {"account": state["account"], "amount": decision.amount})
        return {"decision": decision.model_dump()}

    return iso.run(step, agent="langgraph-refund-node", isolation="serializable")

# graph.add_node("refund", refund_node)
```

### CrewAI (illustrative)

Wrap a tool function so every call is one transaction.

```python
from crewai.tools import tool
from isolate_tx import Isolate

iso = Isolate()

@tool("Approve refund")
def approve_refund(account: str, amount_cents: int) -> str:
    """Approve a refund if the account's budget allows it."""
    def step(tx):
        available = int(tx.read(f"budgets/{account}") or "0")
        if available < amount_cents:
            return f"declined: only {available} cents left"
        tx.write(f"budgets/{account}", str(available - amount_cents))
        tx.after_commit("issue-refund", {"account": account, "amount": amount_cents})
        return "approved"

    return iso.run(step, agent="crewai-support", isolation="serializable")
```

### OpenAI Agents SDK (illustrative)

Same pattern inside a `function_tool`; use `AsyncIsolate` if your tools are async.

```python
from agents import function_tool
from isolate_tx import AsyncIsolate

iso = AsyncIsolate()

@function_tool
async def approve_refund(account: str, amount_cents: int) -> str:
    """Approve a refund if the account's budget allows it."""
    async def step(tx):
        available = int(await tx.read(f"budgets/{account}") or "0")
        if available < amount_cents:
            return "declined"
        await tx.write(f"budgets/{account}", str(available - amount_cents))
        await tx.after_commit("issue-refund", {"account": account, "amount": amount_cents})
        return "approved"

    return await iso.run(step, agent="openai-agents-refunds", isolation="serializable")
```

If the LLM call happens inside the transaction, call `tx.record_tokens(n)` with the tokens it used,
so `/v1/stats` can show how many tokens conflicts cost you.

## Development

```bash
cd clients/python
python -m unittest discover -s tests
```

The tests run against an in-memory fake of the HTTP API (`tests/fake_server.py`), so no server is
needed. The full API is documented in [`docs/http-api.md`](../../docs/http-api.md).

## License

MIT
