# Python SDK

> Write services, virtual objects and workflows in Python with the cairnflow package, serve them, and call them with the Python client.

Source: https://cairnflow.dev/docs/develop/python

The Python SDK, package `cairnflow`, has the same model as the TypeScript SDK: handlers replay
from a journal, side effects go through `ctx.run`, and results reach your code in the order they
were recorded. It needs Python 3.11 or newer and has no runtime dependencies. It is licensed under
Apache-2.0 and is in beta (version `0.1.0b0`).

The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the
same in Python; this page lists what is spelled differently.

## Install

```sh
pip install cairnflow
```

To install from a local checkout of the repository instead: `pip install ./sdk/python`.

Two optional extras:

| Extra | Adds | Needed for |
|---|---|---|
| `cairnflow[bidi]` | `h2` | Streaming mode (`BIDI_STREAM`) in the built-in server |
| `cairnflow[crypto]` | `cryptography` | Faster verification of request signatures; a pure-Python fallback is built in |

## A first service

```python title="service.py"
import asyncio
import os
from dataclasses import dataclass

from cairnflow import Context, TerminalError, VirtualObject, serve

orders = VirtualObject("OrderService")

@dataclass
class Order:
    amount: int

def charge(amount: int) -> str:
    return f"receipt-{amount}"  # a payment provider in real life

@orders.handler()
async def submit(ctx: Context, order: Order) -> dict:
    if order.amount <= 0:
        raise TerminalError("amount must be positive", 400)  # retrying bad input is useless
    total = (await ctx.get("total")) or 0  # None: the key does not exist
    await ctx.sleep(1)  # durable timer, in seconds
    receipt = await ctx.run("charge", charge, order.amount)
    ctx.set("total", total + order.amount)
    return {"receipt": receipt, "total": total + order.amount}

@orders.handler(kind="shared")  # runs alongside the exclusive handlers, reads state only
async def get_total(ctx: Context) -> int:
    return (await ctx.get("total")) or 0

asyncio.run(
    serve(
        [orders],
        host="0.0.0.0",  # the default, 127.0.0.1, is unreachable from outside a container
        port=int(os.environ.get("PORT", "9080")),
        identity_keys=[os.environ["CAIRN_IDENTITY_KEY"]],
    )
)
```

Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with
the service's public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`.

## Services and handlers

| Declared with | Kind |
|---|---|
| `Service(name)` | A plain service: no key, no state |
| `VirtualObject(name)` | A virtual object: state per key; handlers are exclusive unless declared `kind="shared"` |
| `Workflow(name)` | A workflow: exactly one `@wf.main()` handler (named `run` by default) that runs once per workflow ID, plus `@wf.handler()` shared handlers |

- A handler is `async def h(ctx)` or `async def h(ctx, input)`. The handler name defaults to the
  function name; pass `@svc.handler("name")` to choose another.
- Input and output are JSON. An input annotated with a dataclass or a Pydantic model is converted
  for you, and dataclasses and Pydantic models are serialized on the way out.
- Shared handlers must not write state; the runtime rejects their writes with code `571`.

Handler options go in `options=HandlerOptions(...)` on the service or on one handler. Durations
are a `timedelta` or a number of **seconds** (the TypeScript SDK uses milliseconds):

```python
from datetime import timedelta
from cairnflow import HandlerOptions, RetryPolicy, Service

agent = Service(
    "Agent",
    options=HandlerOptions(
        inactivity_timeout=timedelta(minutes=10),
        retry_policy=RetryPolicy(max_attempts=5, on_max_attempts="PAUSE", initial_interval=0.2),
    ),
)
```

`HandlerOptions` fields: `inactivity_timeout`, `retry_policy`, `journal_retention`, `log_level`,
`trace`, `log_flush`. `RetryPolicy` fields: `initial_interval`, `max_interval`,
`exponentiation_factor`, `max_attempts`, `on_max_attempts`. Their meaning is in
[Handler options](/docs/develop/services#handler-options). As in TypeScript, the SDK declares an
`inactivity_timeout` of 15 minutes when you set none.

## The context

| | Python |
|---|---|
| State | `await ctx.get(k)`, `ctx.set(k, v)`, `ctx.clear(k)`, `ctx.clear_all()`, `await ctx.state_keys()` |
| Steps | `await ctx.run(name, fn, *args, cancellable=False, **kwargs)`; `fn` can be sync or async |
| Timers | `await ctx.sleep(seconds_or_timedelta, name="sleep")` |
| Calls | `await ctx.call(service, handler, input, key=..., idempotency_key=..., placement="spread")`, `ctx.send(..., delay=...)`, `ctx.scoped(scope, limit_key).call(...)` |
| Signals | `await ctx.signal(name)`, `ctx.send_signal(invocation_id, name, value)` |
| Awakeables | `awk_id, fut = ctx.awakeable()`, then `await fut` |
| Promises | `await ctx.promise(name).get()`, `.peek()`, `.resolve(v)`, `.reject(message, code)` |
| Other invocations | `await ctx.attach(invocation_id)`, `await ctx.get_output(invocation_id)`, `ctx.continue_as_new(input)` |
| Combinators | `await ctx.all([f1, f2])`, `await ctx.race([f1, f2])`; `asyncio.gather` over branches works too |
| Streams, logs, traces | `ctx.stream(name, durable=False).append(record)`, `ctx.log.info(msg, attrs)`, `async with ctx.trace.span(name) as s:` |
| Artifacts | `ref = ctx.artifact.put(data, "image/png")`, `await ctx.artifact.get(ref)`, `configure_artifacts(base_url, headers)` |
| Identity | `ctx.key`, `ctx.invocation_id`, `ctx.attempt`, `ctx.schedule` (a `(name, at_ms)` tuple or `None`), `ctx.random()` |

The rules of handler code are the same as in TypeScript, with one addition:

1. Use `ctx.random()`, not the `random` module.
2. Read the clock only inside `ctx.run`.
3. **Do all I/O inside `ctx.run`.** Handler code runs on a deterministic event loop that refuses
   network I/O on purpose; `ctx.run` functions run on the server's normal event loop.

## Errors

- `TerminalError(message, code=500)` fails the invocation without a retry.
- `PauseError(message, code=500)` pauses it until someone resumes it.
- Any other exception fails the turn, which is retried with backoff.
- Raised inside a `ctx.run` function, `TerminalError` or `RunFailure` is recorded as the step's
  result: the function does not run again, and `ctx.run` raises a `TerminalError` with the same
  code and message on every replay.

See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies.

## Serving

| Entry point | Where |
|---|---|
| `await serve(services, host="127.0.0.1", port=9080, **options)` | The built-in server. `start(...)` does the same and returns the `asyncio.Server` |
| `app(services, **options)` | An ASGI application for uvicorn, hypercorn or any ASGI server |
| `cairnflow.aws_lambda.lambda_handler(services, **options)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2) |

Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass
`protocol_mode="BIDI_STREAM"`: the built-in server then needs the `bidi` extra, and under ASGI it
needs a server that speaks cleartext HTTP/2 on the same port as HTTP/1.1, such as hypercorn
(uvicorn has no HTTP/2). On Cairnflow Cloud an `https://` endpoint is called in request-response
mode unless you register it with `"transport": "declared"`
([Deployments](/docs/cloud/deployments#transport)).

Options, as keyword arguments:

| Option | Default | Meaning |
|---|---|---|
| `identity_keys` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is emitted once per process |
| `identity_hosts` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) |
| `protocol_mode` | `"REQUEST_RESPONSE"` | Or `"BIDI_STREAM"` |
| `compression` | `True` | Accept gzip request bodies and compress large responses |
| `replay_cache` | `True` (`False` on Lambda) | Keep the journal of running invocations in memory so only new entries are sent |
| `max_protocol_version` | `6` | Pin an older protocol version |
| `segment_origins`, `value_cache_bytes`, `max_value_bytes`, `max_turn_value_bytes` | as in TypeScript | Downloading large values stored as segments |

## Client

```python title="app.py"
import asyncio
import os

from cairnflow import InvocationFailed, connect

async def main() -> None:
    c = connect(os.environ["CAIRN_URL"], api_key=os.environ["CAIRN_KEY"])
    order = c.object("OrderService", "order-42")
    print(await order.call("submit", {"amount": 100}))  # waits for the result

    h = await order.send("submit", {"amount": 5})  # returns once the invocation is durable
    try:
        print(await h.attach(timeout=60))
    except InvocationFailed as e:
        print("failed:", e.code, e)

asyncio.run(main())
```

- Targets: `c.service(name)`, `c.object(name, key)`, `c.workflow(name, workflow_id)`,
  `c.invocation(id)`, `c.awakeable(id)`, `c.promise(service, key, name)`, `c.schedules`. Each
  target takes `scope=` where it applies.
- `call(handler, input, ...)` waits; `send(handler, input, ...)` returns an invocation handle with
  `attach`, `output`, `status`, `signal` and `cancel`. A workflow client adds `run`, `attach` and
  `output`.
- Every call carries a generated `Idempotency-Key`, kept across the client's own retries;
  `idempotency_key=None` sends none. The client follows the `leader` of a `503` and waits for the
  `Retry-After` of a `429`.
- Errors: `InvocationFailed` (a `TerminalError`), `InvocationPaused`, `AlreadyInvoked`,
  `AttachTimeout`, `CairnHttpError`, as in the [typed client](/docs/develop/client).
- `connect` options: `headers`, `follow_leader`, `max_attempts` (8), `max_elapsed` (30 s),
  `attach_wait` (25 s), `timeout`, `connect_timeout` (10 s), `ssl_context`. Durations are in
  seconds.
- `read_stream(base_url, invocation_id, name, offset=0, headers=...)` is an async iterator over
  a stream's events, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs).

Schedules use keyword arguments in snake case:

```python
await c.schedules.put(
    "nightly-report",
    cron="0 2 * * *",
    time_zone="Europe/Berlin",
    target={"service": "Report", "handler": "build"},
    input={"full": True},
)
```

## Not in the Python SDK

- The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`,
  `cairnChatTransport`): it is specific to that TypeScript library.
- A typed client generated from your service definitions: the Python client addresses handlers by
  name.
