Metadata-Version: 2.4
Name: teepin
Version: 0.3.0rc1
Summary: Python SDK for Teepin Web Services (TWS): Teepin Inference (AI models in confidential enclaves, OpenAI-compatible) and Teepin Storage
Author-email: TEEPIN Team <support@teepin.com>
License: Apache-2.0
Project-URL: Homepage, https://teepin.com
Project-URL: Documentation, https://www.teepin.com/docs/sdks/python
Project-URL: Repository, https://github.com/FlashbackAi/teepin-python
Project-URL: Issues, https://github.com/FlashbackAi/teepin-python/issues
Keywords: teepin,tws,inference,llm,openai,confidential computing,object storage,s3
Classifier: Development Status :: 4 - Beta
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: Framework :: AsyncIO
Classifier: Typing :: Typed
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Archiving
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: cryptography>=42.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Dynamic: license-file

# Teepin SDK for Python

Teepin Web Services runs AI models in confidential enclaves (Teepin Inference) and stores your files (Teepin
Storage). This is the official Python client: a synchronous client on `requests` and an asynchronous one on
`aiohttp`, for Python 3.9 and later.

Links: [Docs](https://www.teepin.com/docs) · [console.teepin.com](https://console.teepin.com) · [teepin.com](https://teepin.com)

## Install

```bash
pip install teepin
```

## Authentication

Create an API key in [console.teepin.com](https://console.teepin.com): open a project, then Settings, then API keys.
A key belongs to one project and has the permissions you give it (for example `inference:invoke`,
`storage:read`, `storage:write`).

The client reads the key from `TEEPIN_API_KEY`, and the address from `TEEPIN_BASE_URL`, when you don't pass them.
A value you pass always wins. The address defaults to `https://api.teepin.com`.

```bash
export TEEPIN_API_KEY=tpk_...
```

```python
from teepin import Client

client = Client()  # reads TEEPIN_API_KEY and TEEPIN_BASE_URL
# or: Client(api_key="tpk_...")

reply = client.chat.completions.create(
    model="teepin/glm-5.3",
    messages=[{"role": "user", "content": "What is TLS? One sentence."}],
    max_tokens=300,
    chat_template_kwargs={"enable_thinking": False},
)
print(reply.choices[0].message.content)
```

Keep your API key on your server: every call sends it.

## Teepin Inference

An OpenAI-compatible chat API. The key needs `inference:invoke`, and may be limited to some models.

### Models

```python
for m in client.models.list():          # the models this key may call
    print(m.id, m.display_name, m.pricing.input_per_million_tokens, m.confidential)
    if m.attestation:                   # a confidential model not fully verified right now
        print("  ", m.attestation.level, m.attestation.warning)
```

### One answer

```python
reply = client.chat.completions.create(
    model="teepin/glm-5.3",
    messages=[{"role": "user", "content": "What is TLS?"}],
    max_tokens=300,
    chat_template_kwargs={"enable_thinking": False},
)
print(reply.choices[0].message.content)
print(reply.usage.total_tokens, reply.request_id, reply.attestation, reply.rate_limit)
```

Only the arguments you give are sent: `max_tokens` or `max_completion_tokens`,
`temperature`, `top_p`, `top_k`, `min_p`, `stop`, `seed`, `n`,
`frequency_penalty`, `presence_penalty`, `repetition_penalty`, `logit_bias`,
`logprobs`, `top_logprobs`, `tools`, `tool_choice`, `response_format`,
`stream_options`, `user` and `chat_template_kwargs` (for example
`{"enable_thinking": False}`). `extra_body={...}` sends fields this SDK does
not know yet. Messages are plain dicts, and content may be OpenAI content parts
(`{"type": "image_url", "image_url": {"url": ...}}`).

Every result keeps the JSON it was read from in `.raw`, so a field the SDK does
not know yet is still there (`reply.raw["new_field"]`).

### Streaming

```python
with client.chat.completions.create(
    model="teepin/glm-5.3",
    messages=[{"role": "user", "content": "Write a haiku about the sea."}],
    stream=True,
    stream_options={"include_usage": True},   # usage on the last chunk
) as stream:
    print(stream.request_id, stream.attestation)  # known as soon as the headers arrive
    for chunk in stream:
        if chunk.choices:
            print(chunk.choices[0].delta.content or "", end="")
print(stream.usage)
```

The stream ends at `[DONE]`. If the model fails mid-stream, or the stream ends without `[DONE]`, iterating raises
`StreamError` (`code` is the server's, for example `stream_error`, or `stream_ended_early`). Leaving the `with`
early closes the connection.

### Reasoning models

Reasoning models (GLM-5.3, for example) think before they answer, and the thinking counts toward `max_tokens`.
With a small limit the answer can come back empty (`content` is `None`, `finish_reason` is `"length"`). For a short
answer, turn thinking off with `chat_template_kwargs={"enable_thinking": False}`, or give it room.

### Confidential models and attestation

A confidential model runs in a hardware enclave that proves what code it runs. Each answer says how far the
enclave was verified in `attestation`: `verified`, `verified-older-release` or `not-verified`. Anything less than
`verified` is a warning to show, never an error. The proof itself, to check yourself:

```python
proof = client.models.attestation("teepin/glm-5.3")   # a dict, as the provider gives it
```

It raises `NotFoundError` with `code` `attestation_not_supported` for a model that is not confidential, and
`model_not_found` for one that does not exist or the key may not call.

### Async

```python
import asyncio
from teepin import AsyncClient

async def main():
    async with AsyncClient() as client:
        reply = await client.chat.completions.create(
            model="teepin/glm-5.3",
            messages=[{"role": "user", "content": "Hello"}],
            max_tokens=300,
            chat_template_kwargs={"enable_thinking": False},
        )
        print(reply.choices[0].message.content)

        stream = await client.chat.completions.create(
            model="teepin/glm-5.3", messages=[{"role": "user", "content": "Hello"}], stream=True
        )
        async with stream:
            async for chunk in stream:
                if chunk.choices:
                    print(chunk.choices[0].delta.content or "", end="")

asyncio.run(main())
```

### Rate limits and retries

Limits are per API key: by default 60 chat completions a minute and 10 at a time. A 429 is a `RateLimitError` with
`retry_after` in seconds.

Teepin Inference has its own rules. The server bills a chat completion once it
has the model's answer, even if the client has gone, so a chat request is sent
again only when it certainly was not billed:

- retried: a `429`; Teepin's own `500 internal_error`, `502 upstream_error`,
  `503 model_unavailable` or `503 billing_unavailable` (told by the OpenAI-style
  error body); a connection that was never opened (refused, or DNS failed);
- never retried: a timeout, or a connection reset or cut after the request was
  sent; a `504`; a `5xx` whose body is not Teepin's (a load balancer's HTML
  page); `400`, `401`, `402`, `403`, `404`, `413`; a stream once it has started.

Reads (`models.list`, `models.attestation`) are retried on any `429`, `5xx` or
connection error. Retries go up to `inference_max_retries` times (2; 0 turns
them off), waiting from 0.5 s up to 8 s with full jitter, or the server's
`Retry-After` up to 30 s.

A chat request waits up to 600 s for its answer, whatever the client's
`timeout`; `create(..., timeout=120)` changes it for one call. For a stream it
is the wait for the headers; after them a stream is cut off only by
`transfer_timeout` seconds without a byte.

### Inference errors

Errors carry `status`, `code`, `type`, `message`, `request_id` and `retry_after` (seconds, when the server sent
`Retry-After`).

| Error | When |
| --- | --- |
| `BadRequestError` | 400 `invalid_request` |
| `UnauthorizedError` | 401 `unauthorized` |
| `NoCreditError` (also `InsufficientCreditError`) | 402 `insufficient_credit`: add credit in the console |
| `ForbiddenError` (also `PermissionDeniedError`) | 403 `missing_scope` (no `inference:invoke`), `forbidden` |
| `NotFoundError` | 404 `model_not_found`, `attestation_not_supported` |
| `TooLargeError` | 413 `body_too_large` |
| `RateLimitError` | 429 `rate_limit_exceeded`, `too_many_concurrent_requests`, `rate_limited` |
| `APIError` | 500 `internal_error`, 502 `upstream_error`, 503 `model_unavailable`, `billing_unavailable` |
| `APIConnectionError` | no answer: the network, a timeout (a chat request is not retried after a timeout) |
| `StreamError` | a stream that failed after it started |

### With the OpenAI SDK

The API is OpenAI-compatible, so OpenAI's own SDK works too:

```python
from openai import OpenAI

openai = OpenAI(base_url="https://api.teepin.com/v1", api_key="tpk_...")
reply = openai.chat.completions.create(
    model="teepin/glm-5.3",
    messages=[{"role": "user", "content": "Hello"}],
)
```

This SDK adds the attestation results, billing-safe retries and Teepin's typed errors.

## Teepin Storage

Buckets and files of any size. Files are encrypted on this device and sent straight to the storage network, and read
straight back from it, every byte verified before you get it. No file byte passes through Teepin's API, which keeps
the catalog and signs each request. The key needs `storage:read` to read and `storage:write` to write. The methods are
listed under [Reference](#reference).

### Buckets and a first file

```python
client.storage.create_bucket("my-bucket")
obj = client.storage.upload_file("my-bucket", "videos/launch.mp4", "launch.mp4")
print(obj.key, obj.size, obj.etag)

client.storage.download_file("my-bucket", "videos/launch.mp4", "copy.mp4")
client.storage.list_buckets()
client.storage.delete_bucket("old-bucket")   # only when it is empty
```

`upload_file` sends a file of any size: up to 16 MiB is packed with other objects into one write, and a larger file
goes in parts sent in parallel. Each request is retried on its own, and the object is checked against the bytes read,
so a corrupted transfer is never reported as success. `download_file` fetches a large object in parallel windows, all
pinned to the same version of the object, each byte verified before it is written. It writes a temporary file that is
renamed into place only when the whole object has been checked.

### Upload

```python
s = client.storage

# bytes, or a binary file from where it stands
s.upload("b", "data.bin", b"...", content_type="application/octet-stream", metadata={"owner": "ana"})

# progress and part size
s.upload_file("b", "big.iso", "big.iso", part_size=64 << 20,
              progress=lambda done, total: print(f"{done}/{total}"))

# many files at once: one result per file, and one file's failure never fails another
results = s.upload_files("b", ["a.jpg", "b.jpg"], prefix="photos/")
failed = [r for r in results if not r.saved]

# after a crash: finish what an earlier process left
s.resume_uploads()

# a stream of unknown size (a pipe, a socket; or an async iterable with AsyncClient)
import sys
s.upload_stream("b", "backup.tar", sys.stdin.buffer)
```

How many packs and parts are in flight adapts to the network, up to `upload_concurrency`. A large file and a run of
`upload_files` are journaled in the state directory (`state_dir`), so `resume_uploads()` finishes them after a crash.
`list_upload_runs()` shows the runs kept there, and `clean_uploads()` removes old ones. A stream isn't journaled: if it
fails, upload it again. `list_uploads` and `abort_upload` show and cancel a bucket's open uploads in parts.

On a slow connection, uploads use smaller requests. The client measures how fast its uploads to storage go, and
when a request would take more than about 4 minutes, packs shrink below 9 MiB, an object too large for one such request
(over 5 MiB) goes in parts instead of a pack, and new uploads use smaller parts (down to 5 MiB, the smallest allowed). A
file that still can't be sent, because even 5 MiB parts would be too slow or it would need more than 3,000 parts, raises
`TooLargeError` with `reason="connection_speed"` before anything is sent.

### Download

```python
s.download_file("b", "big.iso", "/tmp/big.iso")     # parallel windows, temp file + rename
data = s.download_bytes("b", "small.json")           # into memory
with open("out.log", "wb") as f:
    s.download_stream("b", "app.log", f)               # in order, to any writable

with s.get_object("b", "app.log", range=(0, 1023)) as r:   # streamed
    head = r.read()

with s.open_object("b", "video.mp4") as f:           # a seekable, read-only file
    f.seek(1 << 20)
    chunk = f.read(4096)

# many objects at once, one result each; run again to go on after an interruption
results = s.download_files("b", ["a.jpg", "b.jpg"], "out/")
results = s.download_prefix("b", "photos/", "out/", skip_existing=True)
```

A window that breaks off goes on from its last verified bytes. If the object is replaced mid-download,
`ObjectChangedError` is raised. The whole object is checked against its SHA-256 (`ChecksumMismatchError`).

### Listing

```python
page = s.list_objects("b", prefix="photos/", delimiter="/", limit=100)
page.objects, page.prefixes, page.next_cursor   # pass next_cursor as cursor= for the next page

for obj in s.iter_objects("b", "photos/"):      # every object, pages fetched as needed
    print(obj.key, obj.size)
```

### ETags

The ETag of an object is the SHA-256 of its bytes, however it was uploaded. ETags are unquoted. To tell whether a
local file matches an object:

```python
from teepin import compute_etag

same = compute_etag("big.iso") == s.stat_object("b", "big.iso").etag
```

An object uploaded in parts by an earlier release of this SDK has `<SHA-256 of the parts' SHA-256s>-<parts>` as its
ETag. For one of those, pass the part size it was uploaded with: `compute_etag(path, part_size, obj.part_count)`
(`part_size_for(size)` gives those releases' default).

### Delete

```python
s.delete_object("b", "app.log")
s.delete_object("b", "app.log", if_match=etag)   # only if it still has stat_object's etag, else PreconditionFailedError
s.delete_objects("b", ["a.txt", "b.txt"])   # up to 1000 a request
s.rename_object("b", "draft.txt", "final.txt")   # instant at any size
```

### Share links

A share link opens a page on the console that anyone with the link can use without signing in. The page decrypts
the file in their browser; the bytes never pass through Teepin's servers.

```python
link = s.create_link("b", "report.pdf", expires_in=3600)   # 15 minutes by default, at most 24 hours
print(link.url, link.expires_at)
s.create_link("b", "report.pdf", disposition="attachment")   # download only, never shown in the page
```

Links are for browsers. Programs read objects with `get_object`, `download_file` and the rest.

### Storage retries

A request that fails for a passing reason is sent again after a wait with full jitter, or the server's
`Retry-After`. It is always retried on `429`, `502` and `503`. It is retried on `500`, `504` or a broken connection
only when sending it twice is harmless: reads, deletes, and each step of an upload. A rename can't be repeated, so it
is retried only when it never reached the server. Errors record the number of tries in `err.attempts`.

While the storage network or the API is unavailable, an upload waits for it, up to `upload_wait` seconds (600), then
raises `StorageUnavailableError`. Nothing is reported saved that isn't.

When an answer is lost after the server acted, the SDK recovers rather than failing:

- A bucket that turns out to exist on a retry is fetched.
- A delete or cancel whose object is gone on a retry succeeds.
- A rename whose source is gone on a retry returns the destination.
- An upload whose commit answer was lost commits again, and gets the stored result.

## Errors

Every error is a `teepin.TeepinError`. API answers raise the subclass for their status and code. Each carries
`status_code`, `code` (for example `object_not_found`), `message` and `request_id` (quote it to support).

| Error | When |
| --- | --- |
| `NotFoundError` | 404: bucket, object, upload |
| `ConflictError` | 409: `bucket_exists`, `bucket_not_empty`, `object_exists` |
| `PreconditionFailedError` | 412: `if_match` / `if_none_match` |
| `TooLargeError` | 413, or `object_too_large`; `reason="connection_speed"`: too large to send at the measured connection speed |
| `NoCreditError` | 402 `insufficient_credit` |
| `OnHoldError` | 402 `storage_on_hold`; `delete_after` says when held data goes |
| `UnauthorizedError`, `ForbiddenError` | 401, 403 (e.g. a key without `storage:write`) |
| `APIConnectionError` | no answer: the network, a timeout |
| `ObjectChangedError` | the object was replaced during a download |
| `ChecksumMismatchError` | the bytes do not match the object's checksum |
| `DataIntegrityError` | bytes that failed a check after a retry; `reason` says which (`ChecksumMismatchError` is one) |
| `KeyErasedError` | 410 `key_erased`: the object's key was erased, so it can never be read |
| `FileChangedError` | a file changed while it was uploaded; `path` names it |
| `StorageUnavailableError` | the storage network didn't come back within `upload_wait` |

Inference adds `BadRequestError`, `RateLimitError` and `StreamError` (see [Inference errors](#inference-errors)).

## Configuration

| Argument | Environment | Default |
| --- | --- | --- |
| `api_key` | `TEEPIN_API_KEY` | none |
| `base_url` | `TEEPIN_BASE_URL` | `https://api.teepin.com` |
| `timeout` | | 60 s for each API call that is not a transfer |
| `transfer_timeout` | | 300 s without a byte before a transfer is cut off |
| `max_retries` | | 4 |
| `inference_max_retries` | | 2, for Teepin Inference (`models`, `chat`) |
| `create(..., timeout=)` | | 600 s for a chat answer (a stream: its headers) |
| `project_id` | | when `api_key` is a signed-in session's token rather than a project key |
| `state_dir` | `TEEPIN_STATE_DIR` | the OS's state directory: where upload runs keep their journals |
| `upload_wait` | `TEEPIN_UPLOAD_WAIT` | 600 s an upload waits for an unavailable storage network |
| `upload_concurrency` | `TEEPIN_UPLOAD_CONCURRENCY` | 32 packs or parts in flight at most |
| `key_cache_ttl` | | 600 s a read keeps an object's data key in memory (0 keeps none) |

## Reference

`client.storage` (on `AsyncClient`, the same methods, awaited):

| Method | Route |
| --- | --- |
| `get_hold()` | `GET /v1/storage/hold` |
| `create_bucket(name)` | `POST /v1/storage/buckets` |
| `list_buckets()` | `GET /v1/storage/buckets` |
| `get_bucket(name)` | `GET /v1/storage/buckets/{bucket}` |
| `delete_bucket(name)` | `DELETE /v1/storage/buckets/{bucket}` |
| `list_objects(bucket, prefix, delimiter, cursor, limit)`, `iter_objects(bucket, prefix)` | `GET .../objects` |
| `delete_objects(bucket, keys)` | `POST .../objects/delete` |
| `stat_object(bucket, key)`, `head_object(bucket, key)` | `GET .../object` |
| `delete_object(bucket, key, if_match)` | `DELETE .../object` |
| `rename_object(bucket, from_key, to_key, overwrite)` | `POST .../object/rename` |
| `list_uploads(bucket, prefix)` | `GET .../uploads` |
| `abort_upload(bucket, upload_id)` | `DELETE .../uploads/{id}` |

Files move straight to and from the storage network, with requests the API signs:

| Method | What it does |
| --- | --- |
| `put_object(bucket, key, body, content_type, metadata, if_match, if_none_match)` | stores bytes, text or a file: packed up to 16 MiB, in parts above; an empty object is `POST .../object/empty` |
| `get_object(bucket, key, range, if_none_match, if_match)` | streams an object or one range, verified |
| `open_object(bucket, key, prefetch)` | a seekable, read-only file |
| `copy_object(bucket, key, source_bucket, source_key, if_match, if_none_match)` | reads the source and uploads it again |

`client.models` and `client.chat.completions` (on `AsyncClient`, awaited):

| Method | Route |
| --- | --- |
| `models.list()` | `GET /v1/models` |
| `models.attestation(model_id)` | `GET /v1/models/attestation?model=<id>` |
| `chat.completions.create(model, messages, stream, ...)` | `POST /v1/chat/completions` |

High level: `upload`, `upload_file`, `upload_files`, `upload_stream`,
`resume_uploads`, `list_upload_runs`, `clean_uploads`, `download`,
`download_file`, `download_bytes`, `download_stream`, `download_files`,
`download_prefix`. Helpers: `teepin.compute_etag`, `teepin.part_size_for`.

## Other APIs

The SDK also has clients for services that aren't offered yet. They answer 404 until they launch.

## Examples

- `examples/inference_sync.py`: models, a chat answer, a stream, an attestation proof
- `examples/inference_async.py`: several chat requests at once, an async stream
- `examples/storage_sync.py`: buckets, a large upload, a parallel download, listing
- `examples/storage_async.py`: several uploads at once, an async stream, reading back

## Development

```bash
pip install -e ".[dev]"
pytest                 # against an in-process fake of the API, with injected faults
black src tests
```

## License

Apache License 2.0. See [LICENSE](LICENSE).
