Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions .github/workflows/ohttp-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: opengradient-ohttp release

# Same flow as release.yml, for packages/opengradient-ohttp:
# bump src/opengradient_ohttp/_version.py in a PR, merge, then
# Actions → "opengradient-ohttp release" → Run workflow (on main).
# Publishes with PyPI trusted publishing (no token): the opengradient-ohttp
# project on pypi.org must list this repo, ohttp-publish.yml and the "pypi"
# environment as a publisher.

on:
workflow_dispatch:

permissions:

Check failure on line 13 in .github/workflows/ohttp-publish.yml

View check run for this annotation

codefactor.io / CodeFactor

excessive-permissions

Overly broad permissions: contents: write is overly broad at the workflow level.
contents: write

Check failure on line 14 in .github/workflows/ohttp-publish.yml

View check run for this annotation

codefactor.io / CodeFactor

excessive-permissions

Overly broad permissions: id-token: write is overly broad at the workflow level.
id-token: write

jobs:
test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: packages/opengradient-ohttp
steps:
- uses: actions/checkout@v4

- name: Install uv
uses: astral-sh/setup-uv@v5

- name: Run tests
run: uv run --python 3.11 --extra test pytest -q

release:
needs: test
runs-on: ubuntu-latest
# Must match the "Environment name" on the PyPI trusted publisher. Its
# protection rules (required reviewers, main only) are set in the repo's
# Settings → Environments → pypi.
environment: pypi
defaults:
run:
working-directory: packages/opengradient-ohttp
steps:
- uses: actions/checkout@v4

- name: Release from main only
if: github.ref != 'refs/heads/main'
run: |
echo "::error::Run this workflow on main (this run is on ${GITHUB_REF_NAME})."
exit 1

- name: Install uv
uses: astral-sh/setup-uv@v5

- name: Set up Python
run: uv python install 3.11

- name: Get version
id: version
run: |
VERSION=$(sed -n 's/^__version__ = "\(.*\)"/\1/p' src/opengradient_ohttp/_version.py)
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "tag=ohttp-v$VERSION" >> "$GITHUB_OUTPUT"

- name: Build package
run: uv build

- name: Publish to PyPI
run: uv publish

- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.version.outputs.tag }}
target_commitish: ${{ github.sha }}
name: opengradient-ohttp ${{ steps.version.outputs.version }}
body: |
`pip install opengradient-ohttp==${{ steps.version.outputs.version }}`

Changes: packages/opengradient-ohttp/CHANGELOG.md
# Keep the SDK's own release as the repo's "Latest".
make_latest: false
files: packages/opengradient-ohttp/dist/*
22 changes: 22 additions & 0 deletions .github/workflows/ohttp-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: opengradient-ohttp tests

on:
pull_request:
paths: ["packages/opengradient-ohttp/**", ".github/workflows/ohttp-*.yml"]
push:
branches: [main]
paths: ["packages/opengradient-ohttp/**", ".github/workflows/ohttp-*.yml"]

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python: ["3.10", "3.11", "3.12", "3.13"]
defaults:
run:
working-directory: packages/opengradient-ohttp
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
- run: uv run --python ${{ matrix.python }} --extra test pytest -q
Comment on lines +12 to +22
10 changes: 10 additions & 0 deletions packages/opengradient-ohttp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Changelog

## 0.1.0

- First release.
- `OHTTPTransport` and `AsyncOHTTPTransport`: httpx transports for the OpenAI SDK that seal chat completions with OHTTP and post them to the DreamFort developer relay (`/api/v1/developer/ohttp`).
- The `Authorization` header comes from the OpenAI client's `api_key`.
- TEE and key selection come from the on-chain registry, cached for 5 minutes. A TEE the relay reports as inactive (`tee_not_active`) is replaced once.
- Single-shot and streaming responses are signature-checked. In a stream, the signed frame is verified before it, and `[DONE]`, are delivered.
- Relay errors map to the OpenAI SDK's typed exceptions. Failures a retry can't fix carry `x-should-retry: false`.
21 changes: 21 additions & 0 deletions packages/opengradient-ohttp/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 OpenGradient

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
135 changes: 135 additions & 0 deletions packages/opengradient-ohttp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# opengradient-ohttp

End-to-end encrypted, TEE-verified chat completions for the OpenAI Python SDK.

- Your request is sealed with Oblivious HTTP (RFC 9458, HPKE) to an attested
OpenGradient TEE.
- The DreamFort relay forwards only the ciphertext, and bills your developer
account.
- Every response is checked against the TEE's on-chain signing key before you
see it.

## Install

```bash
pip install "opengradient-ohttp[openai]"
```

Python 3.10+. The transport itself only needs `httpx`. The `[openai]` extra
pulls in the OpenAI SDK.

## Use

```python
import httpx
from openai import OpenAI
from opengradient_ohttp import OHTTPTransport

client = OpenAI(
base_url="https://ohttp.invalid/v1", # never contacted; the transport routes to the relay
api_key="df_sk_...", # your DreamFort developer API key
http_client=httpx.Client(transport=OHTTPTransport()),
)

completion = client.chat.completions.create(
model="claude-haiku-4-5",
messages=[{"role": "user", "content": "Hello!"}],
max_tokens=200,
)
print(completion.choices[0].message.content)
```

The `.invalid` host is deliberate. If a client is ever built without the
transport, the call fails, so a plaintext prompt is never sent.

### Async

```python
from openai import AsyncOpenAI
from opengradient_ohttp import AsyncOHTTPTransport

client = AsyncOpenAI(
base_url="https://ohttp.invalid/v1",
api_key="df_sk_...",
http_client=httpx.AsyncClient(transport=AsyncOHTTPTransport()),
)
```

### Streaming

`stream=True` works as usual, and deltas arrive as they are decrypted. The
TEE's signed final frame is checked before it (and `[DONE]`) reach you:

- A bad signature raises `opengradient_ohttp.TeeVerificationError` from the
stream.
- A stream that is cut short raises `StreamIncompleteError`.

To get nothing until the whole reply has been verified, use:

```python
OHTTPTransport(verify_before_release=True)
```

### Reading the proof

A non-streaming response carries the proof in its headers:

```python
raw = client.chat.completions.with_raw_response.create(model=..., messages=...)
raw.headers["x-tee-verified"] # "true"
raw.headers["x-tee-id"], raw.headers["x-tee-signature"], raw.headers["x-tee-request-hash"]
completion = raw.parse()
```

The same `tee_*` fields are on the completion object. For a stream, they are
on the last chunk.

## Errors

| HTTP | OpenAI exception | Meaning |
|---|---|---|
| 401 | `AuthenticationError` | The key is invalid or revoked, or its creator left the account |
| 402 | `APIStatusError` | The developer account is out of credits |
| 403 | `PermissionDeniedError` | The key's creator is blocked |
| 429 | `RateLimitError` | The per-account rate limit was hit (retried by the OpenAI SDK) |
| 502 `tee_verification_failed` | `InternalServerError` | The response failed TEE verification (not retried) |
| 503 `tee_registry_unavailable` | `InternalServerError` | The on-chain TEE registry couldn't be read |
| 404 `unsupported_endpoint` | `NotFoundError` | Only `POST /chat/completions` goes over OHTTP |

## Options

All `OHTTPTransport(...)` arguments are keyword-only:

| Argument | Default | |
|---|---|---|
| `relay_url` | `https://chat-api.memchat.io/api/v1/developer/ohttp` | An origin alone gets the developer path appended |
| `api_key` | the OpenAI client's key | Set it to use a different key on the relay |
| `verify_before_release` | `False` | Buffer streams until they are verified |
| `send_model_hint` | `False` | Send the model name in plaintext headers, for relay metrics |
| `registry_rpc_url`, `registry_address` | OpenGradient devnet registry | Where TEEs and their keys come from |
| `tee` | — | Pin one `TeeTarget` instead of reading the registry |
| `tee_cache_ttl` | `300` | Seconds to keep a registry pick |
| `transport` | `httpx.HTTPTransport()` | The outer hop. Pass your own for proxies; TLS verification stays on by default |

## What is sent where

- **The relay (chat-api)** sees:
- your API key;
- the TEE id;
- the ciphertext;
- the size and timing of the request and response.
- **The TEE** sees the plaintext request.
- **Only these request fields are sent**, because the gateway signs them:
- `model`, `messages`, `temperature`, `max_tokens` (or `max_completion_tokens`);
- `stop`, `tools`, `tool_choice`, `response_format`;
- `reasoning_effort`, `aspect_ratio`, `resolution`, `web_search`.

Other fields, such as `top_p` and `seed`, are dropped with a warning, and
`n > 1` is rejected.
- **OpenAI SDK headers** (`x-stainless-*`) are never forwarded.

## Development

```bash
uv run --extra test pytest
```
86 changes: 86 additions & 0 deletions packages/opengradient-ohttp/examples/smoke.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Smoke-test the transport against a live developer relay.

DF_API_KEY=df_sk_... python examples/smoke.py # non-streaming
DF_API_KEY=df_sk_... python examples/smoke.py --stream # streaming
DF_API_KEY=df_sk_... python examples/smoke.py --async # AsyncOpenAI
DF_API_KEY=df_sk_... python examples/smoke.py --relay-url http://localhost:8000

Each request costs a little from the key's developer credits.
"""

from __future__ import annotations

import argparse
import asyncio
import os
import sys

import httpx
from openai import AsyncOpenAI, OpenAI

from opengradient_ohttp import DEFAULT_RELAY_URL, AsyncOHTTPTransport, OHTTPTransport

BASE_URL = "https://ohttp.invalid/v1" # never contacted; the transport routes to the relay


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="claude-opus-5-5")
parser.add_argument("--prompt", default="In one sentence: what is Oblivious HTTP?")
parser.add_argument("--relay-url", default=DEFAULT_RELAY_URL)
parser.add_argument("--stream", action="store_true")
parser.add_argument("--async", dest="use_async", action="store_true")
args = parser.parse_args()

api_key = os.environ.get("DF_API_KEY")
if not api_key:
sys.exit("Set DF_API_KEY to a df_sk_... developer API key.")

if args.use_async:
asyncio.run(run_async(args, api_key))
else:
run_sync(args, api_key)


def run_sync(args: argparse.Namespace, api_key: str) -> None:
client = OpenAI(
base_url=BASE_URL,
api_key=api_key,
http_client=httpx.Client(transport=OHTTPTransport(relay_url=args.relay_url)),
)
messages = [{"role": "user", "content": args.prompt}]
if args.stream:
for chunk in client.chat.completions.create(model=args.model, messages=messages, max_tokens=200, stream=True):
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print("\n[stream verified]")
return

raw = client.chat.completions.with_raw_response.create(model=args.model, messages=messages, max_tokens=200)
completion = raw.parse()
print(completion.choices[0].message.content)
print(f"[verified={raw.headers.get('x-tee-verified')} tee_id={raw.headers.get('x-tee-id')} host={raw.headers.get('x-tee-host')}]")


async def run_async(args: argparse.Namespace, api_key: str) -> None:
client = AsyncOpenAI(
base_url=BASE_URL,
api_key=api_key,
http_client=httpx.AsyncClient(transport=AsyncOHTTPTransport(relay_url=args.relay_url)),
)
messages = [{"role": "user", "content": args.prompt}]
if args.stream:
stream = await client.chat.completions.create(model=args.model, messages=messages, max_tokens=200, stream=True)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print("\n[stream verified]")
else:
completion = await client.chat.completions.create(model=args.model, messages=messages, max_tokens=200)
print(completion.choices[0].message.content)
print("[verified]")
await client.close()


if __name__ == "__main__":
main()
Loading
Loading