# Python SDK

Covers: the `poema` Python package: instances and sandboxes, commands, files, forks, quota and usage.

For: Python developers who drive poema cloud from code.

An instance is a `Task` in code.

The `poema` package drives poema cloud from Python: it makes instances, runs commands and moves files in them, suspends
and forks them, and reads your usage. It is a client of poema's API for Python 3.9 or later, standard library only.

## Install and connect

The [Quickstart](https://client-test.poema.dev/docs.md) installs it. `Poema()` takes the API's URL and your key from the environment, and your namespace
from the key:

```
export POEMA_URL=https://api.client-test.poema.dev
export POEMA_API_KEY=poema_ns_...
```

Without the variables, it uses the key `poema login` keeps.

## An instance, start to end

```python
from poema import Poema

p = Poema()
t = p.create_task("work", ["sleep", "infinity"], gateway="default", debug=True)

box = t.connect()                      # its commands and files, as it was made with debug=True
box.run("git clone --depth 1 https://github.com/octocat/Hello-World repo", cwd="/workspace")
box.write("/workspace/repo/NOTES.md", "look at the README first")
print(box.run("ls -la", cwd="/workspace/repo").stdout)

t.suspend()                            # it stops, its memory and files kept
t.wait("Suspended")
forks = t.fork("try-a", "try-b")       # each runs its command again on a copy of its /workspace
t.resume()                             # it carries on where it stopped
for x in [t, *forks]:
    x.delete()
```

## A sandbox in one block

`p.sandbox()` makes an instance with commands and files on, waits until it is ready and deletes it at the end of the block:

```python
from poema import Poema

p = Poema()
with p.sandbox() as sb:
    sb.upload("train.py", "/workspace/train.py")
    r = sb.run("pip install numpy")
    if r.denied_hosts:               # it failed, and its network blocked these meanwhile
        print(r.hint)                # and where they are allowed
    job = sb.run("python3 train.py", cwd="/workspace", background=True)
    print(job.wait().exit_code)
    sb.download("/workspace/model.bin", "model.bin")
```

## The client: Poema

- `create_task(name, command, image=, env=, workspaces=, gateway=, model=, timeout_seconds=, debug=, wait=, labels=, **spec)`
  creates or updates an instance and waits up to 2 minutes until it runs (`wait=False` returns at once). Past that it
  raises `Timeout` and the instance stays: delete it if you do not want it to start later. `labels=` labels it. `image=` names the image it runs, one of the runtimes
  ([Deploy from git](https://client-test.poema.dev/docs/git.md)); without it, the base image. `debug=True` lets `connect` reach into it. Any other
  field of its spec is a keyword too: without `resources=` it gets 1 vCPU and 256 MiB of memory, and
  `resources={"requests": {"cpu": "2", "memory": "2Gi"}}` asks for 2 vCPUs and 2 GiB.
- `task(name)` is an instance by name.
- `apply(manifest)`, `get(kind, name)`, `list(kind)` and `delete(kind, name)` handle Tasks, Workspaces, Gateways and
  Models as manifests ([Concepts](https://client-test.poema.dev/docs/concepts.md)).
- `set_secret(name, data)` stores provider keys; nothing reads them back.

## An instance: Task

- `Task.get()`, `.wait(phase)`, `.wait_exit()`, `.logs(follow=)` and `.events()` read it. `logs(follow=True)` streams
  for as long as the instance runs, so break out when done. `.ingress()` lists its Gateway's listeners and where each
  is reached, `[]` when it has none.
- `Task.suspend()`, `.resume()`, `.set_timeout(seconds)` and `.delete()` act on it. `suspend()` returns at once: call
  `wait("Suspended")` before `fork`. `resume()` waits until it runs. `set_timeout(seconds)` suspends it that many seconds
  from now, at most your plan's session length; 0 sets that length.
- `Task.fork(*names, memory=, suspend=)` forks a suspended instance into a new one of each name, each running its
  command again on a copy of its workspace, or with `memory=True` going on from a copy of its memory too, and returns
  them. With `suspend=True` each fork stays suspended, copied before the call returns: a snapshot, to resume or fork
  later.
- `Task.connect()` returns a `Sandbox` on the instance (below), so `run(cmd, cwd=, env=, timeout=)`, `read(path)`,
  `write(path, data)`, `list(path)`, `upload` and the rest work on it. A command gets no stdin, and one still running at its timeout is killed and returns its output so far,
  with `timed_out` set.

## Files and background commands: Sandbox

- `Sandbox.upload(src, path)` and `.download(path, dst)` copy a local file to an instance and back, streamed; an upload is
  at most 100 MiB. `.read`, `.write`, `.list`, `.exists`, `.stat`, `.mkdir`, `.remove` and `.move` handle its files, and
  `.run(cmd, background=True)` starts a command that keeps running and returns a `Process` to `wait` for or `kill`.

## For operators

`create_api_key`, `api_keys`, `revoke_api_key`, `audit`, `sessions` and `end_sessions` are for poema's operators: with
your keys they raise `Forbidden`. Make API keys on Settings, Account ([Team and access](https://client-test.poema.dev/docs/team.md)).

## Usage and quota

- `usage(start=None, end=None)` is your organization's use between two days (`YYYY-MM-DD`, both included): model tokens
  and their cost, and compute in vCPU-hours, in total, by model and by day.
- `quota(p.namespace)` is your namespace's quota next to what it has in use: instances, vCPUs, memory, spend,
  vCPU-hours and objects.

## Errors

Every error, a server that does not answer included, is `PoemaError`, with `.status` (0 without an answer), `.code`
and `.message`. Catch a subclass for one case: `Invalid`, `Unauthorized`, `Forbidden`, `NotFound`, `Conflict`,
`QuotaExceeded`, `Unavailable`, `Timeout`.

Last checked: unreleased checkout.
