Metadata-Version: 2.4
Name: graphn
Version: 0.1.6
Summary: Official Python SDK for the Graphn API: custom-model lifecycle, secrets, and OpenAI-compatible inference.
Project-URL: Homepage, https://graphn.ai
Project-URL: Documentation, https://graphn.ai/api
Project-URL: Source, https://github.com/voltagepark/graphn-sdk-python
Project-URL: Issues, https://github.com/voltagepark/graphn-sdk-python/issues
Project-URL: Changelog, https://github.com/voltagepark/graphn-sdk-python/blob/main/CHANGELOG.md
Author: Voltage Park
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (which shall not include Work that is not subject to copyright).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based upon (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "page" as the copyright notice for easier identification within
              third-party archives.
        
           Copyright 2024 Voltage Park
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: custom-models,graphn,inference,llm,openai,voltagepark
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<0.29,>=0.27
Requires-Dist: openai<3,>=1.50
Requires-Dist: pydantic<3,>=2.6
Requires-Dist: typing-extensions>=4.10; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: openapi-python-client>=0.21; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# graphn — Python SDK

[![PyPI](https://img.shields.io/pypi/v/graphn.svg)](https://pypi.org/project/graphn/)
[![Python](https://img.shields.io/pypi/pyversions/graphn.svg)](https://pypi.org/project/graphn/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Tests](https://github.com/voltagepark/graphn-sdk-python/actions/workflows/test.yml/badge.svg)](https://github.com/voltagepark/graphn-sdk-python/actions/workflows/test.yml)

The official Python SDK for [Graphn](https://graphn.ai). Import any
LLM — from HuggingFace or your own S3 bucket — into your workspace,
get an OpenAI-compatible inference endpoint, and call it from Python
in a handful of lines, without standing up a single GPU yourself.

> **v0.1.x scope** — This release line covers **custom-model import
> (HuggingFace + S3) and OpenAI-compatible inference** end-to-end.
> A lot of the broader Graphn platform
> (agents, knowledge bases, workflows, evals, datasets, guardrails,
> billing, full BYO-inference CRUD, etc.) is **not yet exposed**
> through this SDK. Those surfaces will be added in subsequent
> minor releases as their HTTP APIs stabilize. See
> [Scope](#scope) below for the exact list.

```python
import graphn

with graphn.Client() as c:
    model = c.custom_models.create(
        name="my-llama",
        huggingface_model_id="Qwen/Qwen3-0.6B",
        weight_source="huggingface",
    )
    c.custom_models.wait_until_ready(model.id)

    resp = c.chat.completions.create(
        model=model.id,
        messages=[{"role": "user", "content": "Hello!"}],
    )
    print(resp.choices[0].message.content)
```

That's it. Cold-start, retry, OpenAI-compatible serialization, and
the gateway's routing prefix are all handled for you — pass the
bare `model.id` everywhere.

## Install

```bash
pip install graphn
```

Requires Python 3.10+. Tested on 3.10, 3.11, 3.12, 3.13.

## Authentication

The SDK reads credentials from the environment by default:

```bash
export GRAPHN_API_KEY=gn_...           # required
export GRAPHN_WORKSPACE_ID=ws_...      # required
export GRAPHN_BASE_URL=https://cp.graphn.ai      # optional
export GRAPHN_INFERENCE_URL=https://model.graphn.ai  # optional
```

Or pass them explicitly:

```python
client = graphn.Client(api_key="gn_...", workspace_id="ws_...")
```

Get an API key from the [Graphn dashboard](https://graphn.ai).

## Scope

### What's in the box (v0.1.x)

| Module | What it does |
|---|---|
| `client.custom_models` | Import models from HuggingFace, S3 presigned URLs, or S3 + IAM role; list, get, refresh, wake, delete, `wait_until_ready`, validate |
| `client.secrets` | CRUD for workspace secrets (HuggingFace tokens, etc) |
| `client.chat.completions` | OpenAI-compatible chat completions, streaming + non-streaming, **with auto-wake on cold start** |
| `client.models` | List models served by the gateway |
| `client.tts` | Text-to-speech: list voices, synthesize |
| `client.imported_models` | Discover and probe BYO inference endpoints (read-only, no full CRUD yet) |

Both `graphn.Client` and `graphn.AsyncClient` exist with identical APIs.

### What's *not* in the box yet

The Graphn platform is broader than what's exposed here. The
following surfaces exist on the platform but do **not** have SDK
coverage in v0.1.x — file an issue on the
[SDK repo](https://github.com/voltagepark/graphn-sdk-python/issues)
to vote on what you need next:

- **Agents** — defining, running, and inspecting agent workflows
- **Knowledge bases / RAG** — corpus management, retrieval, indexing
- **Workflows** — long-running Temporal-backed orchestration
- **Evals & datasets** — eval suites, dataset upload, run results
- **Guardrails** — policy authoring and inference-time enforcement
- **Imported models (BYO inference) — full CRUD** — only listing
  and probe are exposed today
- **Usage & billing** — usage stats, GPU-hour reporting beyond the
  read-only `client.custom_models.gpu_hours()` helper
- **Workspace / member / API-key administration**

Until they land here, those endpoints can be hit via raw HTTP using
your `gn_...` API key. The control plane is documented at
[graphn.ai/docs/api](https://graphn.ai/docs/api) and the OpenAPI
3.1 spec is mirrored at
[voltagepark/graphn-openapi](https://github.com/voltagepark/graphn-openapi).

## The 80% recipe: import a model and chat with it

```python
import graphn

with graphn.Client() as c:
    # 1. Import the model. Use a workspace secret for gated HF repos.
    model = c.custom_models.create(
        name="my-llama",
        huggingface_model_id="meta-llama/Llama-3.1-8B-Instruct",
        weight_source="huggingface",
        hf_token_secret_id="sec_...",  # optional, only for gated models
    )

    # 2. Wait for the deployment to be live.
    c.custom_models.wait_until_ready(model.id, timeout=1800)

    # 3. Chat. The first call will cold-start the model — the SDK
    #    transparently calls wake() and retries until it serves.
    resp = c.chat.completions.create(
        model=model.id,
        messages=[{"role": "user", "content": "Tell me a joke."}],
        wake_timeout=600,             # max time to wait for cold start
    )
    print(resp.choices[0].message.content)
```

## Importing from S3

If your weights aren't on HuggingFace — fine-tunes, internal models,
licensed checkpoints — import them straight from S3. Two flavors,
both of which still require `huggingface_model_id` (see callout
below).

> **`huggingface_model_id` is required for S3 imports too.** It's
> the canonical identifier for the model — the name the inference
> endpoint advertises and the value you pass in `model` for chat
> completions. Use the upstream `org/model-name` your weights are
> based on (e.g. `Qwen/Qwen3-0.6B`,
> `meta-llama/Llama-3.1-8B-Instruct`). This is the same "Model ID"
> field the web UI requires for S3 imports. Omitting it raises
> `graphn.ValidationError` client-side; passing it but having a
> mismatched archive will surface as a deploy failure on the model
> record.

**Presigned URL** (no AWS credentials shared with Graphn):

```python
model = c.custom_models.create(
    name="my-finetune",
    weight_source="s3_presigned",
    huggingface_model_id="meta-llama/Llama-3.1-8B-Instruct",
    s3_url="https://my-bucket.s3.amazonaws.com/llama-3.1-8b.tar.gz?X-Amz-Algorithm=...",
    gpu_count=1,
)
```

Package the weights as a single `.tar.gz` archive whose top level
is the model directory (the same layout `huggingface-cli download`
produces). Generate the URL with `aws s3 presign s3://my-bucket/llama-3.1-8b.tar.gz`
or the AWS SDK; Graphn pulls weights through the URL on import.
The URL only needs to be live for the import window (allow at
least a few minutes for the download), not for the model's
lifetime.

**IAM role assumption** (for buckets you control, longer-lived
credentials):

```python
model = c.custom_models.create(
    name="my-finetune",
    weight_source="s3_assume_role",
    huggingface_model_id="meta-llama/Llama-3.1-8B-Instruct",
    s3_url="s3://my-bucket/llama-3.1-8b.tar.gz",
    s3_role_arn="arn:aws:iam::123456789012:role/GraphnImport",
    gpu_count=1,
)
```

The role's trust policy must allow Graphn's importer principal to
`sts:AssumeRole`; ask support for the principal ARN to put in your
trust policy. Graphn re-assumes on every import / refresh, so
rotating credentials underneath is safe.

Everything past the create call — `wait_until_ready`, chat completions,
auto-wake, addressing by `model.id` — is identical regardless of
weight source. See [`examples/import_from_s3.py`](examples/import_from_s3.py)
for an end-to-end runnable script.

## Streaming

```python
stream = c.chat.completions.create(
    model=model.id,
    messages=[{"role": "user", "content": "Count to ten."}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
```

## Async

```python
import asyncio
import graphn

async def main() -> None:
    async with graphn.AsyncClient() as c:
        async for m in c.custom_models.list():
            print(m.id, m.name, m.status)

        resp = await c.chat.completions.create(
            model="cm_abc123",
            messages=[{"role": "user", "content": "Hi!"}],
        )
        print(resp.choices[0].message.content)

asyncio.run(main())
```

## Cold starts and auto-wake

Graphn custom models default to **scale-to-zero**: a model with no
traffic for `cooldown_seconds` is descheduled, and the first request
afterwards has to wait for the gateway to spin up a fresh replica
(typically 60–600 seconds depending on weight size).

Without help, the first chat request after a cold period returns:

```
503 Service Unavailable: Model is scaled to zero and is now warming up.
```

The SDK detects this, calls `POST /custom-models/{id}/wake` to nudge
the autoscaler, and retries with exponential backoff until the model
serves or `wake_timeout` (default 180s) elapses. **You don't have to
do anything**, but the knobs are there if you want them:

```python
# Disable auto-wake — you handle the 503 yourself.
c.chat.completions.create(model=..., messages=[...], auto_wake=False)

# Give the warm-up more headroom (e.g. for large models).
c.chat.completions.create(model=..., messages=[...], wake_timeout=900)
```

See [`docs/cold-starts.md`](docs/cold-starts.md) for the full story.

## Drop-in for `openai`

The chat path is OpenAI-compatible all the way down — under the hood
we delegate to the official [`openai` Python SDK](https://github.com/openai/openai-python),
configured against the Graphn gateway. So tools, structured outputs,
multi-modal inputs, function calling, etc. all work out of the box.

If you already have OpenAI-shaped code and just want to point it at
a Graphn model:

```python
from openai import OpenAI

client = OpenAI(
    api_key="gn_...",
    base_url="https://model.graphn.ai/v1",
    default_headers={"X-Workspace-Id": "ws_..."},
)
resp = client.chat.completions.create(
    model="custom:cm_...",  # raw openai client => you type the prefix
    messages=[{"role": "user", "content": "Hello!"}],
)
```

The reason to use `graphn.Client` instead is everything around the
chat call: lifecycle management, secrets, auto-wake, bare-`cm_`
addressing without the wire prefix, typed responses, and a stable
URL contract.

## More examples

See [`examples/`](examples/) for runnable end-to-end scripts:

- [`examples/import_and_chat.py`](examples/import_and_chat.py) — full lifecycle (HuggingFace)
- [`examples/import_from_s3.py`](examples/import_from_s3.py) — S3 presigned + assume-role import
- [`examples/streaming.py`](examples/streaming.py) — streaming chat
- [`examples/async_client.py`](examples/async_client.py) — async usage
- [`examples/openai_compat.py`](examples/openai_compat.py) — drop-in from `openai`

## Configuration reference

| Argument | Default | Notes |
|---|---|---|
| `api_key` | `$GRAPHN_API_KEY` | Bearer token starting with `gn_`. Required. |
| `workspace_id` | `$GRAPHN_WORKSPACE_ID` | Path parameter + `X-Workspace-Id` header. Required. |
| `base_url` | `https://cp.graphn.ai` | Control plane host. |
| `inference_url` | `https://model.graphn.ai` | Inference / OpenAI-compatible host. |
| `timeout` | `60.0` | Per-request HTTPX timeout (seconds). |
| `max_retries` | `2` | Retries on connect failures, 429, and 5xx. |
| `default_headers` | `{}` | Extra headers added to every request. |

## Generating clients in other languages

The OpenAPI 3.1 spec is the source of truth. It's published at:

- **GitHub** — [voltagepark/graphn-openapi](https://github.com/voltagepark/graphn-openapi)
- **Live HTML reference** — [graphn.ai/docs/api](https://graphn.ai/docs/api)
- **Direct download** — `https://cp.graphn.ai/openapi.yaml`

Point your favorite generator at any of these. We test against
`openapi-generator` 6.0+, `openapi-python-client` 0.21+, and
`oapi-codegen` 2.0+.

## Contributing

```bash
git clone https://github.com/voltagepark/graphn-sdk-python
cd graphn-sdk-python
python -m venv .venv && source .venv/bin/activate
pip install -e '.[dev]'

ruff check src tests
pytest
```

Regenerate the typed transport from the upstream spec after a spec
change:

```bash
./scripts/regenerate.sh
```

See [CHANGELOG.md](CHANGELOG.md) for release notes.

## License

Apache 2.0 — see [LICENSE](LICENSE).
